PHP命名空間namespace的定義方法詳解
本文實(shí)例講述了PHP命名空間namespace的定義方法。分享給大家供大家參考,具體如下:
定義命名空間
對于空間的命名,在此我想不用文字解釋,更好的解釋是用實(shí)例來證明:
For example:
下面這段代碼是”test.php”里面的文件:
namespace Test; class Test{ public function Ttest(){ echo "這是Test里面的測試方法"."<br>"; } }
接下來我將用三種不同的方式進(jìn)行訪問,我把這三個訪問程序?qū)懺谝粋€名叫“index.php”的文件中:
方法一:
namespace Index; require 'test.php'; $T=new \Test\Test(); $T->Ttest();
所得結(jié)果為:
這是Test里面的測試方法
方法二:
namespace Index; namespace Test; require 'test.php'; $T=new Test(); $T->Ttest();
所得結(jié)果為:
這是Test里面的測試方法
方法三:
namespace Index; require 'test.php'; use Test\Test; $T=new Test(); $T->Ttest();
所得結(jié)果為:
這是Test里面的測試方法
注: namespace Index可寫可不寫,這只是index.php文件的空間命名。這三種方法所得結(jié)果都是一樣的。
定義子命名空間
定義:
與目錄和文件的關(guān)系很象,PHP 命名空間也允許指定層次化的命名空間的名稱。因此,命名空間的名字可以使用分層次的方式定義。
實(shí)例如下圖,這是我自定義的項(xiàng)目目錄:
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
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《php面向?qū)ο蟪绦蛟O(shè)計(jì)入門教程》、《PHP基本語法入門教程》、《PHP運(yùn)算與運(yùn)算符用法總結(jié)》、《PHP網(wǎng)絡(luò)編程技巧總結(jié)》、《PHP數(shù)組(Array)操作技巧大全》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家PHP程序設(shè)計(jì)有所幫助。
相關(guān)文章
PHP將回調(diào)函數(shù)作用到給定數(shù)組單元的方法
這篇文章主要介紹了PHP將回調(diào)函數(shù)作用到給定數(shù)組單元的方法,是十分重要的一種應(yīng)用,需要的朋友可以參考下2014-08-08PHP實(shí)現(xiàn)簡單注冊登錄系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了PHP實(shí)現(xiàn)簡單注冊登錄系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2020-12-12PHP把空格、換行符、中文逗號等替換成英文逗號的正則表達(dá)式
這篇文章主要介紹了PHP把空格、換行符、中文逗號等替換成英文逗號的正則表達(dá)式,需要的朋友可以參考下2014-05-05php的mail函數(shù)發(fā)送UTF-8編碼中文郵件時標(biāo)題亂碼的解決辦法
這篇文章主要介紹了php的mail函數(shù)發(fā)送UTF-8編碼中文郵件時標(biāo)題亂碼的解決辦法,需要的朋友可以參考下2015-10-10解決php的“It is not safe to rely on the system’s timezone setti
這篇文章主要介紹了解決php的“It is not safe to rely on the system’s timezone settings”問題的方法,需要的朋友可以參考下2015-10-10