PHP命名空間 namespace 及導入 use 的用法

在PHP中,出現同名函數或是同名類是不被允許的。爲防止編程人員在項目中定義的類名或函數名出現重複衝突,在PHP5.3中引入了命名空間這一概念。

1.命名空間,即將代碼劃分成不同空間,不同空間的類名相互獨立,互不衝突。一個php文件中可以存在多個命名空間,第一個命名空間前不能有任何代碼。內容空間聲明後的代碼便屬於這個命名空間,例如:

<?php
    echo 111;       //由於namespace前有代碼而報錯
    namespace Teacher;
    class Person{
        function __construct(){
            echo 'Please study!';
        }
    }

2.調用不同空間內類或方法需寫明命名空間。例如:

<?php
    namespace Teacher;
    class Person{
        function __construct(){
            echo 'Please study!<br/>';
        }
    }
    function Person(){
        return 'You must stay here!';
    };
    namespace Student;
    class Person{
        function __construct(){
            echo 'I want to play!<br/>';
        }
    }
    new Person();                    //本空間(Student空間)
    new \Teacher\Person();           //Teacher空間
    new \Student\Person();           //Student空間
    echo \Teacher\Person();          //Teacher空間下Person函數
    //輸出:
    I want to play!
    Please study!
    I want to play!
    You must stay here!

3.在命名空間內引入其他文件不會屬於本命名空間,而屬於公共空間或是文件中本身定義的命名空間。例:

首先定義一個1.php和2.php文件:

<?php     //1.php
class Person{
    function __construct(){
            echo 'I am one!<br/>';
        }
}
<?php
namespace Newer;
require_once './1.php';
new Person();      //報錯,找不到Person;
new \Person();     //輸出 I am tow!;
<?php     //2.php
namespace Two
class Person{
    function __construct(){
            echo 'I am tow!<br/>';
        }
}
<?php
namespace New;
require_once './2.php';
new Person();      //報錯,(當前空間)找不到Person;
new \Person();     //報錯,(公共空間)找不到Person;
new \Two\Person();  //輸出 I am tow!;

4.下面我們來看use的使用方法:(use以後引用可簡寫)

    namespace School\Parents;
    class Man{
        function __construct(){
            echo 'Listen to teachers!<br/>';
        }
    }
    namespace School\Teacher;
    class Person{
        function __construct(){
            echo 'Please study!<br/>';
        }
    }
    namespace School\Student;
    class Person{
        function __construct(){
            echo 'I want to play!<br/>';
        }
    }
    new Person();                   //輸出I want to play!
    new \School\Teacher\Person();   //輸出Please study!
    new Teacher\Person();           //報錯
    ----------
    use School\Teacher;  
    new Teacher\Person();           //輸出Please study!    
    ----------
    use School\Teacher as Tc;  
    new Tc\Person();           //輸出Please study!  
    ----------
    use \School\Teacher\Person; 
    new Person();           //報錯
    ----------
    use \School\Parent\Man; 
    new Man();           //報錯
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章