PHP 中的魔术变量(Magic Constants)是一类特殊的预定义常量,它们的值会根据它们在源代码中的上下文自动变化。这些变量对大小写敏感,并且通常以两个下划线(__)开始和结束。PHP魔术变量主要用于获取脚本执行时的相关信息,如文件路径、行号、函数名、类名、命名空间名等。以下是PHP中常见的魔术变量列表及其含义:
__LINE__:返回当前代码行的行号。__FILE__:返回当前正在执行脚本的完整路径和文件名。__DIR__:返回当前文件所在目录的绝对路径(不含文件名)。__FUNCTION__:返回当前函数的名称。__CLASS__:返回当前类的名称。__TRAIT__:返回当前trait的名称(PHP 5.4.0及更高版本)。__METHOD__:返回当前类的方法名(包括类名)。__NAMESPACE__:返回当前命名空间的名称。
还有一个值得注意的是,__halt_compiler() 不是魔术变量,而是一个语言结构,用于在编译时停止编译器,但它的作用和使用场景与其他魔术变量不同。
这些魔术变量在实际开发中非常有用,例如在调试、错误报告以及动态生成代码时,可以提供有关代码执行环境的重要信息。
当然,下面给出PHP魔术变量的每个示例及其在实际应用中的简单演示:
-
__LINE__<?php echo "This line is number " . __LINE__ . ".\n"; // 输出类似:This line is number 3.在这个例子中,
__LINE__返回它所在的代码行号,即输出语句所在的行号。 -
__FILE__<?php echo "Current script's file path is: " . __FILE__ . "\n"; // 输出类似:Current script's file path is: /path/to/your/script.php这里
__FILE__返回包含该行代码的文件的完整路径。 -
__DIR__<?php echo "The current directory is: " . __DIR__ . "\n"; // 输出类似:The current directory is: /path/to/your/此处
__DIR__返回当前文件所在目录的绝对路径,不包括文件名。 -
__FUNCTION__<?php function myFunction() { echo "The name of this function is: " . __FUNCTION__ . "\n"; } myFunction(); // 输出:The name of this function is: myFunction当在函数内部引用
__FUNCTION__时,它会显示当前函数的名称。 -
__CLASS__<?php class MyClass { public function whoAmI() { echo "The name of this class is: " . __CLASS__ . "\n"; } } $obj = new MyClass(); $obj->whoAmI(); // 输出:The name of this class is: MyClass在类的方法中,
__CLASS__返回当前类的名称。 -
__TRAIT__(PHP 5.4+)<?php trait MyTrait { public function whichTrait() { echo "The name of this trait is: " . __TRAIT__ . "\n"; } } class MyClassUseTrait { use MyTrait; } $obj = new MyClassUseTrait(); $obj->whichTrait(); // 输出:The name of this trait is: MyTrait在trait内,
__TRAIT__返回当前trait的名称。 -
__METHOD__<?php class MyClass { public function myMethod() { echo "The fully qualified method name is: " . __METHOD__ . "\n"; } } $obj = new MyClass(); $obj->myMethod(); // 输出:The fully qualified method name is: MyClass::myMethod__METHOD__返回当前类方法的全名,包括类名和方法名。 -
__NAMESPACE__<?php namespace MyNamespace; class MyClass { public function showNamespace() { echo "The current namespace is: " . __NAMESPACE__ . "\n"; } } $obj = new MyClass(); $obj->showNamespace(); // 输出:The current namespace is: MyNamespace在命名空间内的类或函数中,
__NAMESPACE__返回当前的命名空间名称。