duandong1869 2017-09-21 11:01
浏览 79
已采纳

在为数组赋值时,有没有理由在PHP中使用=>而不是=?

Please note that I have already read Reference — What does this symbol mean in PHP? and What Does This Mean in PHP -> or => and I know that what => do in PHP.

My question is different.

Generally most programming languages use = to assign value to another.

Example 01

$my_name = "I am the Most Stupid Person"; //Yes, that is my name in SO :-)

Example 02

$cars = array();

$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";

Now let see following example.

$myArray = array(
    0 => 'Big',
    1 => 'Small',
    2 => 'Up',
    3 => 'Down'
);

Here is also what happen is we have assigned 'Big' for $myArray['0'].

But here we used => instead of =. Is there any special reason that PHP was designed that way?

  • 写回答

2条回答 默认 最新

  • douxian1923 2017-09-21 11:11
    关注

    Consistency of syntax is important, here I would say using => in arrays is to ensure = still works. For example:

    $a = 5;
    

    Sets the variable $a to 5.

    $a = $b = 5;
    

    Sets the variable $a and $b to 5. That is = as an operator assigns the right hand side to the left hand side (if possible) and its result is also the right hand side. So now, in the context of an array:

    $a = array(
        0 => 'foo'
      );
    

    Now $a[0] is 'foo'.

    $a = array(
        0 => $b = 'foo'
      );
    

    Now $a[0] and $b are both 'foo'. Now think about this:

    $b = 0;
    $a = array(
        $b => 'foo'
      );
    

    Simply means $a[$b], that is, $a[0] is 'foo'. If PHP used = for array keys:

    $b = 1;
    $a = array(
        $b = 'bar'
      );
    

    What is the value of $a? Is it [1 => 'bar']? Or is it [0 => 'bar']? Did $b get the value 'bar'? Or was it only used as a key?

    As you can see, the parser would be very confusing this way, and there would be no way to allow keys defined by variables with this syntax.

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

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?