0

Let me explain my problem with my code. This works:

$multiarray = array(
    'multikey1' => '',
    'multikey2' => ''
);
$array = array(
    'key1' => '',
    'key2' => '',
    'key3' => '',
    'key4' => $multiarray 
);
print_r($array);

This does not work:

class Array {

    public static $multiarray = array(
        'multikey1' => '',
        'multikey2' => '',
        'multikey3' => ''
    );

    public $array = array(
        'key1' => '',
        'key2' => self::$multiarray
    );
}

$array = new Array;

This does not work unfortunately. Any idea how to solve this?

3
  • 7
    Can't create a class with the name Array. It's reserved. Commented Dec 13, 2012 at 18:10
  • @bobthyasian, thanks, but in my real code I ofcourse don't name that class Array, it just serves as an example Commented Dec 13, 2012 at 18:12
  • For future reference, while a short example is always appreciated, try to pick one that doesn't include unrelated bugs... Commented May 23, 2014 at 19:31

1 Answer 1

1

You can't initialize member variables to anything that is not constant, and you're trying include another array as a member variable, which would require runtime execution.

Also note that the Array class name is invalid, as it conflicts with the reserved word array used to create an array.

From the manual:

This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

The workaround is to set your variable in the constructor:

class Array2 {
    public static $multiarray = array(
        'multikey1' =>  '',
        'multikey2' =>  '',
        'multikey3' =>  ''
    );

    public $array;

    function __construct() {
        $this->array = array(
            'key1'  =>  '',
            'key2'  =>  self::$multiarray
        );
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your answer! I am trying to comprehend your answer but I don't understand it. Could you illustrate your point maybe?
@Orhan classes are considered to be blueprints, and their property definitions need to be independent of any runtime environment or variables. Use the constructor to initialise properties that you want to contain variables (as nickb shows in the answer).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.