• 首页
  • vue
  • TypeScript
  • JavaScript
  • scss
  • css3
  • html5
  • php
  • MySQL
  • redis
  • jQuery
  • namespace关键字和__NAMESPACE__常量

    (PHP 5 >= 5.3.0, PHP 7)

    PHP支持两种抽象的访问当前命名空间内部元素的方法,__NAMESPACE__魔术常量和namespace关键字。

    常量__NAMESPACE__的值是包含当前命名空间名称的字符串。在全局的,不包括在任何命名空间中的代码,它包含一个空的字符串。

    Example #1 __NAMESPACE__ 示例,在命名空间中的代码

    <?php
    namespace MyProject;
    echo '"', __NAMESPACE__, '"'; // 输出 "MyProject"
    ?>
    

    Example #2 __NAMESPACE__ 示例,全局代码

    <?php
    echo '"', __NAMESPACE__, '"'; // 输出 ""
    ?>
    
    常量__NAMESPACE__在动态创建名称时很有用,例如:

    Example #3 使用__NAMESPACE__动态创建名称

    <?php
    namespace MyProject;
    function get($classname)
    {
        $a = __NAMESPACE__ . '\\' . $classname;
        return new $a;
    }
    ?>
    

    关键字namespace可用来显式访问当前命名空间或子命名空间中的元素。它等价于类中的self操作符。

    Example #4 namespace操作符,命名空间中的代码

    <?php
    namespace MyProject;
    use blah\blah as mine; // see "Using namespaces: importing/aliasing"
    blah\mine(); // calls function MyProject\blah\mine()
    namespace\blah\mine(); // calls function MyProject\blah\mine()
    namespace\func(); // calls function MyProject\func()
    namespace\sub\func(); // calls function MyProject\sub\func()
    namespace\cname::method(); // calls static method "method" of class MyProject\cname
    $a = new namespace\sub\cname(); // instantiates object of class MyProject\sub\cname
    $b = namespace\CONSTANT; // assigns value of constant MyProject\CONSTANT to $b
    ?>
    

    Example #5 namespace操作符,全局代码

    <?php
    namespace\func(); // calls function func()
    namespace\sub\func(); // calls function sub\func()
    namespace\cname::method(); // calls static method "method" of class cname
    $a = new namespace\sub\cname(); // instantiates object of class sub\cname
    $b = namespace\CONSTANT; // assigns value of constant CONSTANT to $b
    ?>
    
    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.
    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
    ?>