魔术常量
__LINE__
用来获取文件中的当前行号。
<?php
var_dump(__LINE__); // int(3)
__FILE__
用来获取当前文件的完整路径和文件名。
<?php
var_dump(__FILE__);
__DIR__
用来获取当前文件所在的目录。
<?php
var_dump(__DIR__);
__FUNCTION__
用来获取当前函数的名称。
<?php
/**
* Return the name of the current function.
*
* @param void
* @return string
*/
function foo(): string
{
return __FUNCTION__;
}
var_dump(foo()); // string(3) "foo"
__CLASS__
用来获取当前类的名称。
<?php
class Foo
{
/**
* Return the name of the current class.
*
* @param void
* @return string
*/
public static function method(): string
{
return __CLASS__;
}
}
var_dump(Foo::method()); // string(3) "Foo"
__TRAIT__
用来获取当前 Trait 的名称。
<?php
trait Foo
{
/**
* Return the name of the current trait.
*
* @param void
* @return string
*/
public static function method(): string
{
return __TRAIT__;
}
}
class Bar
{
use Foo;
}
var_dump(Bar::method()); // string(8) "Foo"
__METHOD__
用来获取当前类的方法名。
<?php
class Foo
{
/**
* Return the method name of the current class.
*
* @param void
* @return string
*/
public static function method(): string
{
return __METHOD__;
}
}
var_dump(Foo::method()); // string(11) "Foo::method"
__NAMESPACE__
用来获取当前命名空间的名称(区分大小写)。
<?php
namespace Foo;
class Bar
{
/**
* Return the name of the current namespace.
*
* @param void
* @return string
*/
public static function method(): string
{
return __NAMESPACE__;
}
}
var_dump(Bar::method()); // string(3) "Foo"