【问题标题】:PHP namespace reachabilityPHP 命名空间可达性
【发布时间】:2014-06-23 11:48:04
【问题描述】:

为什么我不能达到这样的常量?我怎样才能到达它?

index.php:

namespace core;

const CONSTANT = 1;

include_once("lib/somefile.php");

/*------------------------*/

lib/somefile.php:

namespace core\lib;

echo CONSTANT; /*doesn't work */
echo core\CONSTANT; /* doesn't work either */

【问题讨论】:

  • echo \core\CONSTANT ?
  • 那么这个问题就结束了?考虑删除它
  • @DamienPirsy 你说得对,我必须在开头添加一个 \,以明确 tis 来自全球。你会发这个吗?

标签: php file hierarchy


【解决方案1】:

使用echo \core\CONSTANT;

core\CONSTANT 会查看相同的命名空间 (core\lib),因为它可以与文件系统一起使用,它会加载 \core\lib\core\CONSTANT,这是错误的命名空间路径。

您需要从根命名空间 (\) 开始,并遵循与文件系统路径相同的规则。

【讨论】:

    【解决方案2】:

    index.php:

    namespace core;
    
    const CONSTANT = 1;
    
    include_once("lib/somefile.php");
    
    /*------------------------*/
    

    lib/somefile.php:

    namespace core\lib;
    
    use core;
    
    echo core\CONSTANT; /* works*/
    

    您必须使用 use 关键字才能与其他命名空间交互。

    正如 Damien Pirsy 提到的,你也可以在 echo 前面写一个\,以澄清这个常量来自全局命名空间:

    namespace core\lib;
    
    echo \core\CONSTANT; /* works*/
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-03
      • 2020-01-14
      • 2014-08-12
      • 1970-01-01
      • 2012-02-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多