Home >php教程 >PHP源码 >PHP namespaces and dynamic language features

PHP namespaces and dynamic language features

伊谢尔伦
伊谢尔伦Original
2016-11-23 10:55:372757browse

PHP 命名空间的实现受到其语言自身的动态特征的影响。因此,如果要将下面的代码转换到命名空间中:

Example #1 动态访问元素

example1.php:

<?php
    class classname
    {
        function __construct()
        {
            echo __METHOD__,"\n";
        }
    }
    function funcname()
    {
        echo __FUNCTION__,"\n";
    }
    const constname = "global";
    $a = &#39;classname&#39;;
    $obj = new $a; // prints classname::__construct
    $b = &#39;funcname&#39;;
    $b(); // prints funcname
    echo constant(&#39;constname&#39;), "\n"; // prints global
?>

必须使用完全限定名称(包括命名空间前缀的类名称)。注意因为在动态的类名称、函数名称或常量名称中,限定名称和完全限定名称没有区别,因此其前导的反斜杠是不必要的。

Example #2 动态访问命名空间的元素

<?php
    namespace namespacename;
    class classname
    {
        function __construct()
        {
            echo __METHOD__,"\n";
        }
    }
    function funcname()
    {
        echo __FUNCTION__,"\n";
    }
    const constname = "namespaced";
    include &#39;example1.php&#39;;
    $a = &#39;classname&#39;;
    $obj = new $a; // prints classname::__construct
    $b = &#39;funcname&#39;;
    $b(); // prints funcname
    echo constant(&#39;constname&#39;), "\n"; // prints global
    /* 注意如果使用双引号, 一定要使用"\\namespacename\\classname"进行转义 */
    $a = &#39;\namespacename\classname&#39;;
    $obj = new $a; // prints namespacename\classname::__construct
    $a = &#39;namespacename\classname&#39;;
    $obj = new $a; // also prints namespacename\classname::__construct
    $b = &#39;namespacename\funcname&#39;;
    $b(); // prints namespacename\funcname
    $b = &#39;\namespacename\funcname&#39;;
    $b(); // also prints namespacename\funcname
    echo constant(&#39;\namespacename\constname&#39;), "\n"; // prints namespaced
    echo constant(&#39;namespacename\constname&#39;), "\n"; // also prints namespaced
?>


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn