溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

PHP中命名空間namespace怎么定義

發(fā)布時間:2021-08-06 10:11:02 來源:億速云 閱讀:146 作者:小新 欄目:開發(fā)技術

這篇文章主要介紹了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 命名空間也允許指定層次化的命名空間的名稱。因此,命名空間的名字可以使用分層次的方式定義。

實例如下圖,這是我自定義的項目目錄:

PHP中命名空間namespace怎么定義

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中命名空間namespace怎么定義”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關注億速云行業(yè)資訊頻道,更多相關知識等著你來學習!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI