php 命名空間

2021-07-25 01:45:11 字數 2325 閱讀 9982

使用命名空間:別名/匯入,

允許通過別名引用或匯入外部的完全限定名稱,是命名空間的乙個重要特徵。這有點類似於在類 unix 檔案系統中可以建立對其它的檔案或目錄的符號連線。

所有支援命名空間的php版本支援三種別名或匯入方式:為類名稱使用別名、為介面使用別名或為命名空間名稱使用別名。php 5.6開始允許匯入函式或常量或者為它們設定別名。

在php中,別名是通過操作符 use 來實現的. 下面是乙個使用所有可能的五種匯入方式的例子:

namespace

foo;

usemy\full\classname

asanother;

// 下面的例子與 use my\full\nsname as nsname 相同

usemy\full\nsname;

// 匯入乙個全域性類

usearrayobject;

// importing a function (php 5.6+)

usefunction

my\full\functionname;

// aliasing a function (php 5.6+)

usefunction

my\full\functionname

asfunc;

// importing a constant (php 5.6+)

useconst

my\full\constant;

$obj = new

namespace\another; // 例項化 foo\another 物件

$obj = new another; // 例項化 my\full\classname 物件

nsname\subns\func(); // 呼叫函式 my\full\nsname\subns\func

$a = new arrayobject(array(1)); // 例項化 arrayobject 物件

// 如果不使用 "use \arrayobject" ,則例項化乙個 foo\arrayobject 物件

func(); // calls function my\full\functionname

echo constant; // echoes the value of my\full\constant

注意對命名空間中的名稱(包含命名空間分隔符的完全限定名稱如 foo\bar以及相對的不包含命名空間分隔符的全域性名稱如 foobar)來說,前導的反斜槓是不必要的也不推薦的,因為匯入的名稱必須是完全限定的,不會根據當前的命名空間作相對解析。

為了簡化操作,php還支援在一行中使用多個use語句

example #2 通過use操作符匯入/使用別名,一行中包含多個use語句

use my\full

\classname as another, my\full

\nsname;

$obj = new another; // 例項化 my\full

\classname 物件

nsname\subns

\func(); // 呼叫函式 my\full

\nsname

\subns

\func

另外,匯入操作只影響非限定名稱和限定名稱。完全限定名稱由於是確定的,故不受匯入的影響。

use my\full\classname as another, my\full\nsname;

$obj = new another; // instantiates object of class

my\full\classname

$obj = new \another; // instantiates object of class

another

$obj = new another\thing; // instantiates object of class

my\full\classname\thing

$obj = new \another\thing; // instantiates object of class

another\thing

全域性空間

如果沒有定義任何命名空間,所有的類與函式的定義都是在全域性空間,與 php 引入命名空間概念前一樣。在名稱前加上字首 \ 表示該名稱是全域性空間中的名稱,即使該名稱位於其它的命名空間中時也是如此。

namespace a\b\c;

/* 這個函式是 a\b\c\fopen */

function fopen()

php 命名空間,PHP使用命名空間

介紹 命名空間中的類,函式或常量可以通過以下方式使用 在當前命名空間中使用類 指定相對於當前命名空間的命名空間 提供命名空間的全限定名稱 從當前命名空間 在此示例中,從test1.php載入了命名空間。沒有命名空間引用的函式或類名稱將訪問當前命名空間中的功能或類名稱 示例 test1.php nam...

php命名空間

namespace misszhou function var dump a 1 var dump var dump 1 表示呼叫全域性 解決常量的衝突問題 有點像子目錄的概念 namespace meizi 必須放第一行 include func.inc.php function one func...

PHP命名空間

命名空間是抽象的容器,建立它是為了容納物件名稱的邏輯群組。在其他語言中這是為人熟知的功能,而且有時呈現為包或者模組。指令碼每天越來越大,也越來越複雜,這使得發明新的識別符號難上加難。使用use語句可以講命名空間匯入區域性命名空間,而且可以使用更方便的名稱作為它的別名。如果檔案中有多個命名空間,必須使...