http://cn2.php.net/manual/en/language.constants.predefined.php
Magic constants ¶
PHP provides a large number of predefined constants to any script which it runs. Many of these constants, however, are created by various extensions, and will only be present when those extensions are available, either via dynamic loading or because they have been compiled in.
There are eight magical constants that change depending on where they are used. For example, the value of __LINE__
depends on the line that it's used on in your script. These special constants are case-insensitive and are as follows:
Name | Description |
---|---|
__LINE__ | The current line number of the file. |
__FILE__ | The full path and filename of the file. If used inside an include, the name of the included file is returned. Since PHP 4.0.2, __FILE__ always contains an absolute path with symlinks resolved whereas in older versions it contained relative path under some circumstances. |
__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. (Added in PHP 5.3.0.) |
__FUNCTION__ | The function name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the function name as it was declared (case-sensitive). In PHP 4 its value is always lowercased. |
__CLASS__ | The class name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the class name as it was declared (case-sensitive). In PHP 4 its value is always lowercased. 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. (Added in PHP 5.4.0) As of PHP 5.4 this constant returns the trait as it was declared (case-sensitive). The trait name includes the namespace it was declared in (e.g. Foo\Bar). |
__METHOD__ | The class method name. (Added in PHP 5.0.0) The method name is returned as it was declared (case-sensitive). |
__NAMESPACE__ | The name of the current namespace (case-sensitive). This constant is defined in compile-time (Added in PHP 5.3.0). |
See also get_class(), get_object_vars(), file_exists() and function_exists().
User Contributed Notes 12 notes
the difference between
__FUNCTION__ and __METHOD__ as in PHP 5.0.4 is that
__FUNCTION__ returns only the name of the function
while as __METHOD__ returns the name of the class alongwith the name of the function
class trick
{
function doit()
{
echo __FUNCTION__;
}
function doitagain()
{
echo __METHOD__;
}
}
$obj=new trick();
$obj->doit();
output will be ---- doit
$obj->doitagain();
output will be ----- trick::doitagain
Note that __FILE__ has a quirk when used inside an eval() call. It will tack on something like "(80) : eval()'d code" (the number may change) on the end of the string at run-time. The workaround is:
$script = php_strip_whitespace('myprogram.php');
$script = str_replace('__FILE__',"preg_replace('@\(.*\(.*$@', '', __FILE__,1)",$script);
eval($script);
Since namespace were introduced, it would be nice to have a magic constant or function (like get_class()) which would return the class name without the namespaces.
On windows I used basename(__CLASS__). (LOL)
As pointed out by david at thegallagher dot net[1], you can NOT use the defined() function to check if a *magic* constant is defined. Often seen, but will not work:
<?php
if (!defined('__MAGIC_CONSTANT__')) {
// FAIL! even if __MAGIC_CONSTANT__ is defined,
// defined('__MAGIC_CONSTANT__') will ALWAYS return (bool)false.
}
?>
Now, raat1979 at gmail dot com[2] pointed out a solution to check if a magic constant is defined or not (which actually works reliable). Thanks to dynamic typecasting in PHP, if a constant lookup fails PHP interprets the given constant name as string (note that a notice is thrown nonetheless. thus, use "@" to suppress it).
<?php
var_dump(@UNDEFINED_CONSTANT_NAME); //prints: string(23) "UNDEFINED_CONSTANT_NAME"
?>
Meaning we can check for all constants - including magic constants (eg __DIR__) - as follows:
<?php
if (@__DIR__ == '__DIR__'){
// __DIR__ was interpreted as string. thus, (magic) constant __DIR__ is not defined.
}
?>
However, what is wrong in raat1979 at gmail dot com's note[2] is this comment:
> "remember that because they are MAGIC constants defining __DIR__ is completely useless"
In fact, you *can* define magic constants (as long as they haven't been defined before, of course).
Based on all I've read and tested today, here is my code I use to make the `__DIR__` magic constant work with all PHP versions (4.3.1 - 5.5.3):
<?php
// Ensure that PHP's magic constant __DIR__ is defined - no matter of the PHP version.
// If magic __DIR__ constant is not defined, define it.
(@__DIR__ == '__DIR__') && define('__DIR__', dirname(__FILE__));
// All PHP versions (>= 4.3.1) can use the magic __DIR__ constant now..
// Demo (outputs and VLD opcodes) here: http://3v4l.org/bm6e1
?>
[1] http://us2.php.net/manual/en/language.constants.predefined.php#107614
[2] http://us2.php.net/manual/en/language.constants.predefined.php#113130
You cannot check if a magic constant is defined. This means there is no point in checking if __DIR__ is defined then defining it. `defined('__DIR__')` always returns false. Defining __DIR__ will silently fail in PHP 5.3+. This could cause compatibility issues if your script includes other scripts.
Here is proof:
<?php
echo (defined('__DIR__') ? '__DIR__ is defined' : '__DIR__ is NOT defined' . PHP_EOL);
echo (defined('__FILE__') ? '__FILE__ is defined' : '__FILE__ is NOT defined' . PHP_EOL);
echo (defined('PHP_VERSION') ? 'PHP_VERSION is defined' : 'PHP_VERSION is NOT defined') . PHP_EOL;
echo 'PHP Version: ' . PHP_VERSION . PHP_EOL;
?>
Output:
__DIR__ is NOT defined
__FILE__ is NOT defined
PHP_VERSION is defined
PHP Version: 5.3.6
Further to my previous note, the 'object' element of the array can be used to get the parent object. So changing the get_class_static() function to the following will make the code behave as expected:
<?php
function get_class_static() {
$bt = debug_backtrace();
if (isset($bt[1]['object']))
return get_class($bt[1]['object']);
else
return $bt[1]['class'];
}
?>
HOWEVER, it still fails when being called statically. Changing the last two lines of my previous example to
<?php
foo::printClassName();
bar::printClassName();
?>
...still gives the same problematic result in PHP5, but in this case the 'object' property is not set, so that technique is unavailable.
Further clarification on the __TRAIT__ magic constant.
<?php
trait PeanutButter {
function traitName() {echo __TRAIT__;}
}
trait PeanutButterAndJelly {
use PeanutButter;
}
class Test {
use PeanutButterAndJelly;
}
(new Test)->traitName(); //PeanutButter
?>
__DIR__ is actually equivalent to realpath(dirname(__FILE__)).
Here's a modified version of the one-liner eyecatchup at gmail dot com[1] wrote:
<?php
// ensure the __DIR__ constant is defined for PHP 4.0.6 and newer
(@__DIR__ == '__DIR__') && define('__DIR__', realpath(dirname(__FILE__)));
?>
Their version also works on PHP 4.0.6, but doesn't use realpath. __DIR__ is an absolute path to the current file.
[1] http://www.php.net/manual/en/language.constants.predefined.php#113233
Magic constants can not be tested with defined($name)
<?php
if(!defined(__DIR__)){
//will not work
}
?>
when __DIR__ is not defined and you use it anyway php assumes you meant '__DIR__' and throws a notice.
because of this assumption we can do:
<?php
if(@__DIR__ == '__DIR__'){
echo 'magic __DIR__ constant NOT defined';
//insert this code where needed, remember that because they are MAGIC constants defining __DIR__ is completely useless
}echo{
echo 'magic __DIR__ constant IS defined';
}
?>
There is no way to implement a backwards compatible __DIR__ in versions prior to 5.3.0.
The only thing that you can do is to perform a recursive search and replace to dirname(__FILE__):
find . -type f -print0 | xargs -0 sed -i 's/__DIR__/dirname(__FILE__)/'
The __CLASS__ magic constant nicely complements the get_class() function.
Sometimes you need to know both:
- name of the inherited class
- name of the class actually executed
Here's an example that shows the possible solution:
<?php
class base_class
{
function say_a()
{
echo "'a' - said the " . __CLASS__ . "<br/>";
}
function say_b()
{
echo "'b' - said the " . get_class($this) . "<br/>";
}
}
class derived_class extends base_class
{
function say_a()
{
parent::say_a();
echo "'a' - said the " . __CLASS__ . "<br/>";
}
function say_b()
{
parent::say_b();
echo "'b' - said the " . get_class($this) . "<br/>";
}
}
$obj_b = new derived_class();
$obj_b->say_a();
echo "<br/>";
$obj_b->say_b();
?>
The output should look roughly like this:
'a' - said the base_class
'a' - said the derived_class
'b' - said the derived_class
'b' - said the derived_class
Note that __CLASS__ contains the class it is called in; in lowercase. So the code:
class A
{
function showclass()
{
echo __CLASS__;
}
}
class B extends A
{
}
$a = new A();
$b = new B();
$a->showclass();
$b->showclass();
A::showclass();
B::showclass();
results in "aaaa";