【问题标题】:Undefined constant error when using namespace in Symfony在 Symfony 中使用命名空间时出现未定义的常量错误
【发布时间】:2017-10-09 11:56:20
【问题描述】:

PHP 5.6 Symfony 3

我在包中有一个文件,其中包含一个带有已定义常量的命名空间...

constfile.php

<?php
namespace Some\Interesting\ConstFile {
    const NAME_OF_CONSTANT = 'Some Constant';
}
namespace Some\Interesting\ConstFile\Specific {
    const NAME_OF_SPECIFIC_CONSTANT = 'Some Specific Constant';
}

然后我在另一个包中有另一个文件,我正在尝试使用常量...

stuff.php

<?php
namespace More\Cool\Stuff;

use Some\Interesting\ConstFile as CF;
use Some\Interesting\ConstFile\Specific as CFS;

class Stuff {
    public function doit() {    
        $output->writeln(CF\NAME_OF_CONSTANT);
        $output->writeln(CFS\NAME_OF_SPECIFIC_CONSTANT);
    }
}

PHPStorm 对此设置没有任何抱怨。但是,当我运行它时,我收到“致命错误:stuff.php 中未定义的常量 NAME_OF_CONSTANT”错误。

【问题讨论】:

    标签: php namespaces constants


    【解决方案1】:

    当您错误并在命名空间前加上反斜杠时,也可能会发生此错误。 Use 语句可以以 \namespace 为前缀> 不能。 命名空间中的反斜杠导致 php 将整行理解为常量。

    【讨论】:

      【解决方案2】:

      尝试加载此类文件时自动加载效果不佳,请尝试手动包含原始文件。

      require 'path/to/constfile.php'
      

      【讨论】:

        猜你喜欢
        • 2013-06-03
        • 1970-01-01
        • 1970-01-01
        • 2013-06-12
        • 1970-01-01
        • 1970-01-01
        • 2020-11-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多