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

报告相同问题?

悬赏问题

  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决