您的位置:首页 > 编程语言 > PHP开发

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

2017-09-24 22:30 465 查看
在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 name
echo "This file full path and file name is '" . __FILE__ . "'.\n";

// This prints file full path, without file name
echo "This file full path is '" . __DIR__ . "'.\n";

// This prints current line number on file
echo "This is line number " . __LINE__ . ".\n";

// Really simple basic test function
function test_function_magic_constant() {
echo "This is from '" . __FUNCTION__ . "' function.\n";
}

// Prints function and used namespace
test_function_magic_constant();

// Really simple class for testing magic constants
class TestMagicConstants {
// Prints class name
public function printClassName() {
echo "This is " . __CLASS__ . " class.\n";
}

// Prints class and method name
public function printMethodName() {
echo "This is " . __METHOD__ . " method.\n";
}

// Prints function name
public 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的相关开发中,使用魔术变量将会使得开发变得更加的简便。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  php namespace 魔术变量