开发者

PHP: alternate associative array notation not allowed inside class?

开发者 https://www.devze.com 2023-03-17 06:54 出处:网络
In PHP, this associative array notation works outside of a class: $array[\'a\'] = array(\'a\', \'b\', \'c\', \'d\');

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 ge开发者_StackOverflowt really cumbersome with bigger arrays.


$array['a'] = array('a', 'b', 'c', 'd');
$array['b'] = array('1', '2', '3', '4');

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 ;-)


I don't know the technical reason why you can't do like you describe. Probably something silly and very low level. You could easily get around this, for a concrete class anyway, by setting the arrays in the constructor like this:

class foo {

protected $bar = new array();

  function __construct() {
    $array['a'] = array('a', 'b', 'c', 'd');
    $array['b'] = array('1', '2', '3', '4');

    $this->bar = $array;
  }

}


Don't know exact reason. Suppose php still has some kinks in its code.

class Foo {
    protected $array=array();
    public function Foo()
    {
    $array['b'] = array('1', '2', '3', '4');
    }
}

But this compiles ok. So you can just put the code in the constructor.


Something wrong with

public function __construct() {
   $this->array['a'] = array('a', 'b', 'c', 'd');
   $this->array['b'] = array('1', '2', '3', '4');
}

I can only postulate on the technical reasons for this. A guess is that [] is an operation in php which can change the size in memory of a variable. Class definitions should have a constant space in memory when initialized.

0

精彩评论

暂无评论...
验证码 换一张
取 消