PHP 魔术常量

2019-04-03  本文已影响0人  DragonsLong

过去我认为已经记得很牢的知识,今天也是模棱两可。好记性,不如烂笔头。

做笔记的意义在于,对模棱两可的知识不断的复盘,达到看到 苹果,就想起 Apple , 就能想起 A-P-P-L-E 的境界一般。

魔术常量

魔术常量(Magical Constants) 的值会伴随着它们在代码中的位置改变而改变。

常用的 8 个 PHP 魔术常量有:

名称 说明
__LINE__ the current line number of the file
__FILE__ the full path and filename of the file
__DIR__ the directory of the file
__NAMESPACE__ the name of the current namespace
__CLASS__ the class name
__FUNCTION__ the function name
__METHOD__ the class method name
__TRAIT__ The trait name. The trait name includes the namespace it was declared in

源码说明

<?php
namespace magic\consts;

echo __NAMESPACE__; // magic\consts

class Test extends Base
{
    public function __construct()
    {
        parent::__construct();
        var_dump(__CLASS__); //magic\consts\Test
    }

    public function echomethod()
    {
        var_dump(__METHOD__); // magic\consts\Test::echomethod
    }

    public function echofunction()
    {
        var_dump(__FUNCTION__); // echofunction
    }
}

class Base
{
    public function __construct()
    {
        var_dump(__CLASS__); //magic\consts\Base
    }
}

$test = new Test();
$test->echomethod();
$test->echofunction();

var_dump(__DIR__); // F:\ProgramLife\WWW\Demo\magic_const
var_dump(__FILE__); // F:\ProgramLife\WWW\Demo\magic_const\const.php
var_dump(__LINE__); // 50
上一篇 下一篇

猜你喜欢

热点阅读