PHP魔術常量

魔術常數是PHP中的預定義常量,根據它們的使用而改變。 它們以雙下劃線(__)開頭,以雙下劃線結尾。

它們類似於其他預定義的常量,但是它們隨著上下文的改變而改變它們的值,它們被稱為魔術常量。

下表中定義了八個魔法常量。 它們不區分大小寫

常量名稱 描述
__LINE__ 表示使用當前行號。
__FILE__ 表示檔的完整路徑和文件名。 如果它在include中使用,則返回包含檔的名稱。
__DIR__ 表示檔的完整目錄路徑。 等同於dirname(__file__)。 除非它是根目錄,否則它沒有尾部斜杠。 它還解析符號鏈接。
__FUNCTION__ 表示使用它的函數名稱。如果它在任何函數之外使用,則它將返回空白。
__CLASS__ 表示使用它的函數名稱。如果它在任何函數之外使用,則它將返回空白。
__TRAIT__ 表示使用它的特徵名稱。 如果它在任何函數之外使用,則它將返回空白。 它包括它被聲明的命名空間。
__METHOD__ 表示使用它的類方法的名稱。方法名稱在有聲明時返回。
__NAMESPACE__ 表示當前命名空間的名稱。

實例

下麵來看看一個上面的每個魔法常量的例子。

檔案名:magic.php

<?php

    echo "<h3>Example for __LINE__</h3>";
    echo "You are at line number " . __LINE__ . "<br><br>";// print Your current line number i.e;3
    echo "<h3>Example for __FILE__</h3>";
    echo __FILE__ . "<br><br>";//print full path of file with .php extension
    echo "<h3>Example for __DIR__</h3>";
    echo __DIR__ . "<br><br>";//print full path of directory where script will be placed
    echo dirname(__FILE__) . "<br><br>"; //its output is equivalent to above one.
    echo "<h3>Example for __FUNCTION__</h3>";
    //Using magic constant inside function.
    function cash(){
        echo 'the function name is '. __FUNCTION__ . "<br><br>";//the function name is cash.
    }

    cash();

    //Using magic constant outside function gives the blank output.
    function test_function(){
        echo 'HYIIII';
    }

    test_function();
    echo  __FUNCTION__ . "<br><br>";//gives the blank output.

    echo "<h3>Example for __CLASS__</h3>";
    class abc
    {
        public function __construct() {
            ;
        }

        function abc_method(){
        echo __CLASS__ . "<br><br>";//print name of the class abc.
        }
    }
    $t = new abc;
    $t->abc_method();

    class first{
        function test_first(){
            echo __CLASS__;//will always print parent class which is first here.
        }
    }

    class second extends first
    {
        public function __construct() {
            ;
        }
    }
    $t = new second;
    $t->test_first();

    echo "<h3>Example for __TRAIT__</h3>";
    trait created_trait{
        function abc(){
            echo __TRAIT__;//will print name of the trait created_trait
        }
    }

    class anew{
        use created_trait;
    }
    $a = new anew;
    $a->abc();
    echo "<h3>Example for __METHOD__</h3>";

    class meth{
        public function __construct() {
            echo __METHOD__ . "<br><br>";//print meth::__construct
        }
        public function meth_fun(){
            echo __METHOD__;//print meth::meth_fun
        }
    }
    $a = new meth;
    $a->meth_fun();

    echo "<h3>Example for __NAMESPACE__</h3>";
    class name{
        public function __construct() {
            echo 'This line will be printed on calling namespace';
        }
    }
    $clas_name= __NAMESPACE__ .'\name';
    $a = new $clas_name;

?>

執行上面代碼得到以下結果 -


上一篇: PHP常量 下一篇: PHP數據類型