为什么 PHP 数组在其元素被引用分配时被修改? [英] Why does a PHP array get modified when it's element is reference-assigned?

查看:21
本文介绍了为什么 PHP 数组在其元素被引用分配时被修改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当引用赋值数组的元素时,数组的内容被修改:

When ref-assigning an array's element, the contents of the array are modified:

$arr = array(100, 200);
var_dump($arr);
/* shows:
array(2) {
  [0]=>
  int(100)  // ← ← ← int(100)
  [1]=>
  int(200)
}
*/

$r = &$arr[0];
var_dump($arr);
/* shows:
array(2) {
  [0]=>
  &int(100)  // ← ← ← &int(100)
  [1]=>
  int(200)
}
*/

实时运行.(Zend Engine 可以正常工作,而 HHVM 显示Process退出代码 153".)

Live run. (Zend Engine will do fine, while HHVM shows "Process exited with code 153".)

为什么要修改元素?

为什么我们看到的是 &int(100) 而不是 int(100)?

Why do we see &int(100) instead of int(100)?

这看起来很奇怪.这种奇怪的解释是什么?

This seems totally bizarre. What's the explanation for this oddity?

推荐答案

我已经回答了一段时间,但现在找不到答案.我相信它是这样的:

I have answered this a while back, but cannot find the answer right now. I believe it went like this:

引用只是符号表中相同值的附加"条目.符号表只能有它指向的,不能有值中的值.符号表不能指向数组中的索引,它只能指向一个值.因此,当您想要引用数组索引时,该索引处的值会从数组中取出,为其创建一个符号,数组中的插槽获得对该值的引用:

References are simply "additional" entries in the symbol table for the same value. The symbol table can only have values it points to, not values in values. The symbol table cannot point to an index in an array, it can only point to a value. So when you want to make a reference to an array index, the value at that index is taken out of the array, a symbol is created for it and the slot in the array gets a reference to the value:

$foo = array('bar');

symbol | value
-------+----------------
foo    | array(0 => bar)

$baz =& $foo[0];

symbol | value
-------+----------------
foo    | array(0 => $1)
baz    | $1
$1     | bar              <-- pseudo entry for value that can be referenced

因为这是不可能的:

symbol | value
-------+----------------
foo    | array(0 => bar)
baz    | &foo[0]          <-- not supported by symbol table

上面的 $1 只是一个任意选择的伪"名称,与实际的 PHP 语法或内部实际引用的值无关.

The $1 above is just an arbitrarily chosen "pseudo" name, it has nothing to do with actual PHP syntax or with how the value is actually referenced internally.

按照评论中的要求,这里的符号表通常如何与引用一起工作:

As requested in the comments, here how the symbol table usually behaves with references:

$a = 1;

symbol | value
-------+----------------
a      | 1


$b = 1;

symbol | value
-------+----------------
a      | 1
b      | 1


$c =& a;

symbol | value
-------+----------------
a, c   | 1
b      | 1

这篇关于为什么 PHP 数组在其元素被引用分配时被修改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆