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

报告相同问题?

悬赏问题

  • ¥20 基于决策树的数字信号处理,2ask 2psk 2fsk的代码,检查下报错的原因
  • ¥20 python作业求过程
  • ¥15 wincc已组态的变量过多
  • ¥60 如图:直线与椭圆X轴平行,求直线与椭圆任意一点的相切坐标计算公式
  • ¥50 如何用python使用opencv里的cv::cudacodec::VideoWriter函数对视频进行GPU硬编码
  • ¥100 c#solidworks 二次开发 工程图自动标边线法兰 等折弯尺寸怎么标
  • ¥15 halcon DrawRegion 提示错误
  • ¥15 FastAPI Uvicorn启动显示404
  • ¥15 centos7.9脚本,怎么排除特定的访问记录
  • ¥15 关于#Django#的问题:我的静态文件呢?