欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

PHP命名空間namespace的定義方法詳解

 更新時間:2017年03月29日 09:55:39   作者:PHP__廊外詩鴿  
這篇文章主要介紹了PHP命名空間namespace的定義方法,結(jié)合實(shí)例形式詳細(xì)分析了php命名空間namespace及子命名空間的定義方法與相關(guān)注意事項(xiàng),需要的朋友可以參考下

本文實(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)文章

最新評論