PHP:类中不允许使用备用关联数组表示法吗?

PHP:类中不允许使用备用关联数组表示法吗?

问题描述:

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.

在PHP中,此关联数组表示法在类之外工作: p>

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

但在类中,类似的符号会导致错误: p>

  class Foo {
 protected $ array ['a'] = array('a','b','c','d'); 
 protected $ array ['b'] = array('1'  ,'2','3','4'); 
} 
 
 //解析错误:语法错误,意外'[',期待','或';'
  code>   pre> 
 
 

然而这很好用: p>

  class Foo {
 protected $ array = array('a'=> array('  a','b','c','d'),'b'=>数组('1','2','3','4')); 
} 
  code  >  pre> 
 
 

知道发生了什么事吗? 对于更大的数组,允许的表示法会变得非常麻烦。 p> div>

$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.