Array/classes Constant expression contains invalid

2020-03-31 08:08发布

问题:

I can't understand why this doesn't work:

class TestOne
{

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

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

this gives me the error:

Constant expression contains invalid operations

I would like TestOne::$TEST[ "test" ][ "name" ] to contain "result"

回答1:

Constant scalars expressions cannot reference variables (as they are not constant).

You'll have to initialize the property some other way (e.g. through a static accessor) or avoid public static properties altogether.



回答2:

In PHP you can not use other variables while defining the variables of a class.

To give you a simple example,

$test = "result";

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

would've given you the same error because you can not refer to other variables while defining them in a class. Only way you can do it is:

class TestOne
{

    public static $TEST = array(
        "test" => array(
            "name" => "result"
        )
    );
}

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


标签: php arrays