【问题标题】:Array/classes Constant expression contains invalid operations数组/类常量表达式包含无效操作
【发布时间】:2017-06-18 10:28:42
【问题描述】:

我不明白为什么这不起作用:

class TestOne
{

    public static $TEST = array(
        "test" => array( "name" => TestTwo::$TEST2[ "test" ] ) // error line
)}

class TestTwo
{
    public static $TEST2 = array(
        "test" => "result"
    );
}

这给了我错误:

常量表达式包含无效操作

我希望TestOne::$TEST[ "test" ][ "name" ] 包含“结果”

【问题讨论】:

  • PHP 版本?在这里使用。

标签: php arrays


【解决方案1】:

Constant scalars expressions 不能引用变量(因为它们不是常量)。

您必须以其他方式初始化属性(例如通过静态访问器)或完全避免公共静态属性。

【讨论】:

    【解决方案2】:

    在 PHP 中定义类的变量时不能使用其他变量。

    举个简单的例子,

    $test = "result";
    
    class TestOne {
        public static $TEST = $test;
    }
    

    会给你同样的错误,因为你不能在类中定义其他变量时引用它们。唯一可以做到的方法是:

    class TestOne
    {
    
        public static $TEST = array(
            "test" => array(
                "name" => "result"
            )
        );
    }
    
    class TestTwo
    {
        public static $TEST2 = array(
            "test" => "result"
        );
    }
    

    【讨论】:

      猜你喜欢
      • 2018-12-02
      • 2017-04-11
      • 2017-05-16
      • 1970-01-01
      • 2017-03-03
      • 2017-10-19
      相关资源
      最近更新 更多