数组/类常量表达式包含无效操作

时间:2017-02-01 15:40:35

标签: php arrays

我无法理解为什么这不起作用:

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" ]包含"结果"

2 个答案:

答案 0 :(得分:1)

在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"
    );
}

答案 1 :(得分:1)

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

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