doucheng3407 2011-07-02 06:52
浏览 27
已采纳

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.

  • 写回答

4条回答 默认 最新

  • dongyan7950 2011-07-02 06:59
    关注
    $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 ;-)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程