namespace 关键字和 __NAMESPACE__ 常量
(PHP 5 >= 5.3.0, PHP 7, PHP 8)
PHP支持两种抽象的访问当前命名空间内部元素的方法,__NAMESPACE__
魔术常量和 namespace
关键字。
常量 __NAMESPACE__
的值是包含当前命名空间名称的字符串。在全局的,不包括在任何命名空间中的代码,它包含一个空的字符串。
示例 #1 __NAMESPACE__ 示例, 在命名空间中的代码
<?php
namespace MyProject;
echo '"', __NAMESPACE__, '"'; // 输出 "MyProject"
?>
示例 #2 __NAMESPACE__ 示例,全局代码
<?php
echo '"', __NAMESPACE__, '"'; // 输出 ""
?>
__NAMESPACE__
在动态创建名称时很有用,例如:
示例 #3 使用 __NAMESPACE__ 动态创建名称
<?php
namespace MyProject;
function get($classname)
{
$a = __NAMESPACE__ . '\\' . $classname;
return new $a;
}
?>
关键字 namespace
可用来显式访问当前命名空间或子命名空间中的元素。它等价于类中的
self
操作符。
示例 #4 namespace 操作符,命名空间中的代码
<?php
namespace MyProject;
use blah\blah as mine; // 参考 "使用命名空间:别名/导入"
blah\mine(); // 调用函数 MyProject\blah\mine()
namespace\blah\mine(); // 调用函数 MyProject\blah\mine()
namespace\func(); // 调用函数 MyProject\func()
namespace\sub\func(); // 调用函数 MyProject\sub\func()
namespace\cname::method(); // 调用 class MyProject\cname 的静态方法 "method"
$a = new namespace\sub\cname(); // class MyProject\sub\cname 的实例对象
$b = namespace\CONSTANT; // 设置 $b 的值为常量 MyProject\CONSTANT
?>
示例 #5 namespace 操作符, 全局代码
<?php
namespace\func(); // 调用函数 func()
namespace\sub\func(); // 调用函数 sub\func()
namespace\cname::method(); // 调用 class cname 的静态方法 "method"
$a = new namespace\sub\cname(); // class sub\cname 的实例对象
$b = namespace\CONSTANT; // 设置 $b 的值为常量 CONSTANT
?>

User Contributed Notes 3 notes
a dot schaffhirt at sedna-soft dot de ¶
12 years ago
Just in case you wonder what the practical use of the namespace keyword is...
It can explicitly refer to classes from the current namespace regardless of possibly "use"d classes with the same name from other namespaces. However, this does not apply for functions.
Example:
<?php
namespace foo;
class Xyz {}
function abc () {}
?>
<?php
namespace bar;
class Xyz {}
function abc () {}
?>
<?php
namespace bar;
use foo\Xyz;
use foo\abc;
new Xyz(); // instantiates \foo\Xyz
new namespace\Xyz(); // instantiates \bar\Xyz
abc(); // invokes \bar\abc regardless of the second use statement
\foo\abc(); // it has to be invoked using the fully qualified name
?>
Hope, this can save someone from some trouble.
Best regards.
bharatthapa45 at gmail dot com ¶
2 months ago
Difference between __NAMESPACE__ and keyword 'namespace' that I find relevant is when invoking a class:
<?php
namespace MyApp;
class App {
static function app(){
echo 'hello app';
}
}
// this will work:
$obj = new namespace\App::app();
// this will not work
$obj = new __NAMESPACE__\App::app();
// however this will work:
$obj = __NAMESPACE__ . '\App';
$obj::foo();
?>
cornichonche at gmail dot com ¶
4 years ago
The example 4 is wrong.
Using php 7.2
<?php
namespace monProjet;
use function blah\blah as mine;
blah\mine(); // Will NOT work
mine(); // Will work
?>
备份地址:http://www.lvesu.com/blog/php/language.namespaces.nsconstants.php