php的魔术变量__METHOD__、__FUNCTION、__DIR__、__f

来源:互联网 发布:Windows 10 无线网络 编辑:程序博客网 时间:2024/06/14 08:38

在php中提供了__FILE__、__DIR__、__LINE__、__CLASS__、__NAMESPACE__、__METHOD__、__FUNCTION__等魔术变量,其中:

__FILE__:返回该文件的完整路径和文件名。

__DIR__:返回文件的目录。

__LINE__:返回当前文件的行数。

__CLASS__:返回类名。

__NAMESPACE__:返回当前命名空间的名称。

__METHOD__:返回类的方法名。

__FUNCTION__:返回当前函数名。


<?php// Set namespace (works only with PHP 5.3+)namespace TestProject;// This prints file full path and nameecho "This file full path and file name is '" . __FILE__ . "'.\n";// This prints file full path, without file nameecho "This file full path is '" . __DIR__ . "'.\n";// This prints current line number on fileecho "This is line number " . __LINE__ . ".\n";// Really simple basic test functionfunction test_function_magic_constant() {echo "This is from '" . __FUNCTION__ . "' function.\n";}// Prints function and used namespacetest_function_magic_constant();// Really simple class for testing magic constantsclass TestMagicConstants {// Prints class namepublic function printClassName() {echo "This is " . __CLASS__ . " class.\n";}// Prints class and method namepublic function printMethodName() {echo "This is " . __METHOD__ . " method.\n";}// Prints function namepublic function printFunction() {echo "This is function '" . __FUNCTION__ . "' inside class.\n";}// Prints namespace name (works only with PHP 5.3)public function printNamespace() {echo "Namespace name is '" . __NAMESPACE__ . "'.\n";}}// Create new TestMagicConstants class$test_magic_constants = new TestMagicConstants;// This prints class name and used namespace$test_magic_constants->printClassName();// This prints method name and used namespace$test_magic_constants->printMethodName();// This prints function name inside class and used namespace// same as method name, but without class$test_magic_constants->printFunction();// This prints namespace name (works only with PHP 5.3)$test_magic_constants->printNamespace();?>
输出结果:

This file full path and file name is '/tmp/magic_constants/magic.php'.This file full path is '/tmp/magic_constants'.This is line number 13.This is from 'TestProject\test_function_magic_constant' function.This is TestProject\TestMagicConstants class.This is TestProject\TestMagicConstants::printMethodName method.This is function 'printFunction' inside class.Namespace name is 'TestProject'.

这就是php中的相关魔术变量,在php的相关开发中,使用魔术变量将会使得开发变得更加的简便。

原创粉丝点击