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

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

问题描述

当REF-分配的阵列的元件,所述阵列的内容被修改

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引擎会做得很好,而HHVM表演过程退出,code 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天全站免登陆