Last updated on December 13, 2015
Today I would like to given quick introduction on PHP’s magic constants. PHP provides a set of predefined constants and which are available on any script which it runs.
You can also create your own constants by using define()
or const
. But custom defined function will not available globally you should auto load or include the file where the screen runs.
The magic constants names are reserved and with placing two underscores before and after the constant’s word representation.
You can also get the list of defined constants by using built in php’s function get_defined_constants()
.
Here is the few Magic Constants :
Name | Description |
---|---|
__LINE__ |
Returns the line number in the source file the constant appears |
__FILE__ |
The full path and filename of the file with symlinks resolved. If used inside an include, the name of the included file is returned. |
__DIR__ |
The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to dirname(__FILE__). This directory name does not have a trailing slash unless it is the root directory. |
__FUNCTION__ |
The function name. |
__CLASS__ |
The class name. The class name includes the namespace it was declared in (e.g. Foo\Bar). Note that as of PHP 5.4 __CLASS__ works also in traits. When used in a trait method, __CLASS__ is the name of the class the trait is used in. |
__TRAIT__ |
The trait name. The trait name includes the namespace it was declared in (e.g. Foo\Bar). |
__METHOD__ |
The class method name. |
__NAMESPACE__ |
The name of the current namespace. |
Magic constants are very using while debugging application :
if($name == '') { echo('$name has no value on line '.__LINE__.' of ['.__FILE__.']'); }
While including other scripts its good to use ‘__FILE__‘ constant:
require_once(dirname(__FILE__) . '/config/database.php');
You can use dirname(dirname(__FILE__)) to get parent directory.