php使用命名空間 別名 匯入

2021-07-05 13:35:11 字數 2612 閱讀 8429

(php 5 >= 5.3.0)

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

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

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

<?php

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語句

<?php

use my\full

\classname as another, my\full

\nsname;

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

\classname 物件

nsname\subns

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

\nsname

\subns

\func

?>

匯入操作是在編譯執行的,但動態的類名稱、函式名稱或常量名稱則不是。

<?php

usemy\full\classname

asanother, my\full\nsname;

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

$a = 'another';

$obj = new

$a; // 實際化乙個 another 物件

?>

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

<?php

usemy\full\classname

asanother, 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 languages;

class greenlandic

?>

importing rules are per file basis, meaning included files will not inherit the parent file』s importing rules.

注:**php使用命名空間:別名/匯入

使用命名空間 別名 匯入

php 5 5.3.0,php 7 允許通過別名引用或匯入外部的完全限定名稱,是命名空間的乙個重要特徵。這有點類似於在類 unix 檔案系統中可以建立對其它的檔案或目錄的符號連線。所有支援命名空間的php版本支援三種別名或匯入方式 為類名稱使用別名 為介面使用別名或為命名空間名稱使用別名。php 5...

PHP命名空間和別名 匯入(摘要)

支援命名空間,php版本需要 5.3.0。從廣義上來說,命名空間是一種封裝事物的方法。在很多地方都可以見到這種抽象概念。例如,在作業系統中目錄用來將相關檔案分組,對於目錄中的檔案來說,它就扮演了命名空間的角色。具體舉個例子,檔案foo.txt 可以同時在目錄 home greg 和 home oth...

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

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