Skip to main content

PHP Magic Constants

Tags

PHP Logo

If you have spent any time writing Object Oriented PHP or Drupal PHP you will know that there are many instances where it can be handy to know exactly what you are dealing with at a specific point in your code.  For example, possibly you are troubleshooting an issue and cannot figure out why a variable is not acting as it should, or maybe you are writing logging routines to make sure all of your exceptions are logged for future troubleshooting.  Whatever your needs may be it can be very helpful to use PHP Magic constants to assist you in your troubleshooting.  PHP Magic constants are dynamic case-insensitive constants that can output a different value based upon where the constant is placed in the script.  For example __LINE__ on line number 14 in your PHP script will output 14, and __line__ on line 18 will output 18.  Here is a very basic example of using the following constants: __CLASS__, __FUNCTION__, __METHOD__, and __LINE__.  

<?php
 
 class Foo {
   // Use the __CLASS__ constant to log the class
   public $message = '';
 
   function bar_one() {
    	// Use the __CLASS__ and __FUNCTION__ constants to	    	
    	// log the class name and the specific function the
    	// constant is found in.
    	$this->message .= 'Class:  ' . __CLASS__;
    	$this->message .= ', Function: ' . __FUNCTION__;
   }
 
   function bar_two() {
    	// User the __METHOD__ constant to log the class's method
    	$this->message .= ', Method: ' . __METHOD__;
   }
 
   function log_message() {
    	// Name the error log file
    	$error_log = 'error_log_' . date('D_M_j_G_i_s');
 
    	// Use the __LINE__ constant to provide a line number
    	$this->message .= ', Line: ' . __LINE__;
    	// Write the log file
    	file_put_contents($error_log, $this->message, FILE_APPEND);
   }
 }
 
 $object = new Foo();
 $object->bar_one();
 $object->bar_two();
 $object->log_message();
 
 // Outputs
 // Class:  Foo, Function: bar_one, Method: Foo::bar_two, Line: 25
?>

For a complete list of all PHP Magic constants see the documentation here

Image referenced from: https://upload.wikimedia.org/

Member for

3 years 9 months
Matt Eaton

Long time mobile team lead with a love for network engineering, security, IoT, oss, writing, wireless, and mobile.  Avid runner and determined health nut living in the greater Chicagoland area.

Comments

Still learning PHP, but this is great to know! Coding right now and think I might try some of these out!