首頁  >  文章  >  後端開發  >  php命名空間用法詳解

php命名空間用法詳解

*文
*文原創
2017-12-29 18:04:321818瀏覽

本文主要介紹了php中命名空間namespace use用法,結合實例形式分析了PHP中命名空間的定義與使用技巧,所需的朋友可以參考下。希望對大家有幫助。

具體如下:

現在說這個感覺有點過時了,但是感覺用namespace的人還是不多,估計還是因為不習慣吧。

class把一個一個function組織起來,namespace可以理解成把一個一個class,function等有序的組織起來。個人覺得,namespace的主要優勢有

第一,可以更好的管理代碼
第二,文件一多,可以避免class,function的重名
第三,代碼可讀性增強了

1.定義namespace


#
namespace userCenter;
//php代码
namespace userCenter\register;
//php代码
namespace userCenter\login {
 //php代码
}

命名空間不能嵌套或在同一程式碼處聲明多次(只有最後一次會被識別)。但是,你能在同一個檔案中定義多個命名空間化的程式碼,比較適合的做法是每個檔案定義一個命名空間(可以是相同命名空間)。

2. 呼叫namespace


\userCenter\register; //绝对调用
userCenter\login; //相对调用
use userCenter\register; //引用空间
use userCenter\register as reg; //引用空间并加别名

3. 實例說明

login.類.php


<?php
namespace userCenter;
function check_username(){
 echo "login OK<br>";
}
class login{
 public function save(){
 echo "login had saved<br>";
 }
}
?>

regist.class.php


<?php
namespace userCenter\regist
{
 function check_username() {
 echo "regist OK<br>";
 }
 class regist{
 public function save(){
 echo "regist had saved<br>";
 }
 }
}
?>

test.php


<?php
require "login.class.php";
require "regist.class.php";
use userCenter\regist; //使用use调用空间
use userCenter\regist as reg; //as定义别名
echo \userCenter\check_username(); //绝对调用
$login = new \userCenter\login();
echo $login->save();
echo regist\check_username(); //相对调用
echo reg\check_username(); //别名调用
$regist = new reg\regist();
echo $regist->save();

使用use,比絕對呼叫好一點,好比給class,function等加了一個前綴,這樣看起來就比較清楚了。

相關推薦:

php中的命名空間相關概念淺析

#PHP命名空間與自動載入類別

PHP命名空間的使用基礎

#########PHP命名空間的使用基礎#########

以上是php命名空間用法詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn