In PHP, this associative array notation works outside of a class:
$array['a'] = array('a', 'b', 'c', 'd');
$array['b'] = array('1', '2', '3', '4');
But inside a class, similar notation causes an error:
class Foo {
protected $array['a'] = array('a', 'b', 'c', 'd');
protected $array['b'] = array('1', '2', '3', '4');
}
//Parse error: syntax error, unexpected '[', expecting ',' or ';'
And yet this works just fine:
class Foo {
protected $array = array('a'=>array('a', 'b', 'c', 'd'), 'b'=>array('1', '2', '3', '4'));
}
Any idea what’s going on? The allowed notation can get really cumbersome with bigger arrays.
this means the $array var was defined in the first line, in the second you only put stuff into it.
That is why it won’t work in a class, you cannot define the same variable twice.
Even more, the
[]=is a modifying operator, which can not be used in class definition, the same reason you can not use the++sign. Not a deep programming or computer inability to do that, just a design decision not to do logic outside of methods inside a class (As opposed to JS or Ruby for example).Of course, all that behaviour can be changed by “small” C hacking of the engine 😉