woff 發表於 2021-9-12 22:53:53

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();         //報錯
頁: [1]
查看完整版本: PHP名稱空間 namespace 及匯入 use 的用法