php – namespace 命名空間教學介紹
很多個 函式(function) 可以使用 類別(class) 包裝起來;
很多個 類別(class) 可以使用 命名空間(namespace) 包裝起來。
命名空間,可以解決不同人使用同樣名稱的類別,所造成的衝突。例如小明寫了一支取名hello的類別;小華也寫了一支取名hello的類別,一旦同時載入小明寫的跟小華寫的,若不使用命名空間的寫法,就會造成衝突。所以比較建議,命名空間是針對一個檔案使用一個命名空間;後面也舉例一個檔案多個命名空間的寫法。
a.php
<? //小明取名一個叫做 a 的空間,在 namespace 後面的 class 都將會被歸類在 a 底下 namespace a; class hello { static public function get() { return "a get"; } } class byebye { static public function get() { return "a byebye"; } }
b.php
<? //小華取名一個叫做 b 的空間,在 namespace 後面的 class 都將會被歸類在 b 底下 namespace b; class hello { static public function get() { return "a get"; } } class byebye { static public function get() { return "a byebye"; } }
開發者寫的 index.php
<? //載入小明與小華寫的檔案,因為使用了命名空間,所以同樣的 class 名稱不會造成衝突 include_once("a.php"); include_once("b.php"); echo a\hello::get(); //輸出 a get 這是小明寫的 echo b\hello::get(); //輸出 b get 這是小華寫的 echo a\byebye::get(); //輸出 c byebye 這是小明寫的 echo b\byebye::get(); //輸出 d byebye 這是小華寫的
接著是使用 use 來處理的複雜分類方式...
a.php
<? //小明取名一個叫做 a 的空間,在 namespace 後面的 class 都將會被歸類在 a 底下 namespace a\man; class hello { static public function get() { return "a\man hello::get()"; } } class byebye { static public function get() { return "a\man byebye::get()"; } } namespace a\woman; class hello { static public function get() { return "a\woman hello::get()"; } } class byebye { static public function get() { return "a\woman byebye::get()"; } }
b.php
<? //小華取名一個叫做 b 的空間,在 namespace 後面的 class 都將會被歸類在 b 底下 namespace b\man; class hello { static public function get() { return "b\man hello::get()"; } } class byebye { static public function get() { return "b\man byebye::get()"; } } namespace b\woman; class hello { static public function get() { return "b\woman hello::get()"; } } class byebye { static public function get() { return "b\woman byebye::get()"; } }
index.php
<? // 載入小明與小華寫的檔案,因為使用了命名空間,所以同樣的 class 名稱不會造成衝突 include_once("a.php"); include_once("b.php"); //一、 // 使用 a\man 並取別名為 a_man。當然也可以不使用 as 來取別名。 use a\man as a_man; // 使用別名叫做 a_man 底下的類別 hello echo a_man\hello::get(); // 輸出 a\man hello::get() echo "<br>"; echo a_man\byebye::get(); // 輸出 a\man byebye::get() echo "<br>"; // 二、 use a\woman as a_wonan; echo a_wonan\hello::get(); // 輸出 a\woman hello::get() echo "<br>"; // 三、 use b\man as b_man; echo b_man\hello::get(); // 輸出 b\man hello::get() echo "<br>"; // 四、 use b\woman as b_woman; echo b_woman\hello::get(); // 輸出 b\woman hello::get() echo "<br>";