本文實例講述了PHP命名空間namespace的定義方法。分享給大家供大家參考,具體如下:
定義命名空間
對于空間的命名,在此我想不用文字解釋,更好的解釋是用實例來證明:
For example:
下面這段代碼是”test.php”里面的文件:
namespace Test; class Test{ public function Ttest(){ echo "這是Test里面的測試方法"."<br>"; } }
接下來我將用三種不同的方式進行訪問,我把這三個訪問程序寫在一個名叫“index.php”的文件中:
方法一:
namespace Index; require 'test.php'; $T=new \Test\Test(); $T->Ttest();
所得結果為:
這是Test里面的測試方法
方法二:
namespace Index; namespace Test; require 'test.php'; $T=new Test(); $T->Ttest();
所得結果為:
這是Test里面的測試方法
方法三:
namespace Index; require 'test.php'; use Test\Test; $T=new Test(); $T->Ttest();
所得結果為:
這是Test里面的測試方法
注: namespace Index可寫可不寫,這只是index.php文件的空間命名。這三種方法所得結果都是一樣的。
定義子命名空間
定義:
與目錄和文件的關系很象,PHP 命名空間也允許指定層次化的命名空間的名稱。因此,命名空間的名字可以使用分層次的方式定義。
實例如下圖,這是我自定義的項目目錄:
one.php
namespace projectOne\one; class Test{ public function test(){ return "this is a test program"; } }
為了訪問one.php中Test類下的test()方法,我在Two中的代碼如下:
Two.php
namespace projectOne\one; require '../projectOne/One.php'; $O=new Test(); echo $O->test();
Output: this is a test program
同一文件中定義多個命名空間,它們之間相互訪問
test.php
namespace projectOne\one{ class test{ public function hello(){ return "helloworld"; } } } namespace projectOne\Two{ class project{ public function world2(){ return "welcome to china"; } } class project2 extends \projectOne\one\test{ public function wo(){ return "this is my test function ,it is name wo"; } } } namespace projectOne\Two{ $p=new project2(); echo $p->wo()."<br>"; echo $p->hello(); }
output: this is my test function ,it is name wo
helloworld
更多關于PHP相關內容感興趣的讀者可查看本站專題:《php面向對象程序設計入門教程》、《PHP基本語法入門教程》、《PHP運算與運算符用法總結》、《PHP網絡編程技巧總結》、《PHP數組(Array)操作技巧大全》、《php字符串(string)用法總結》、《php+mysql數據庫操作入門教程》及《php常見數據庫操作技巧匯總》
希望本文所述對大家PHP程序設計有所幫助。
【網站聲明】本站除付費源碼經過測試外,其他素材未做測試,不保證完整性,網站上部分源碼僅限學習交流,請勿用于商業用途。如損害你的權益請聯系客服QQ:2655101040 給予處理,謝謝支持。