简体   繁体   English

通过更改函数返回的引用来更改全局数组值

[英]Change global array values by changing the reference returned from a function

It's difficult to explain in word what I'm trying to do, so I'm providing a minimal example, see comments: 很难用语言解释我正在尝试做什么,所以我提供了一个最小的例子,请参阅注释:

$g = array( 
    'a' => array(1, 2, 3), 
    'b' => array(4, 5, 6)
); // A global array

function &search($key) {
    global $g;
    return $g[$key];
}

$a = search('b'); // Now $a should be a reference to $g['b'], right?

$a[2] = 666;
print_r($a); // Ok changed
print_r($g); // Why not changed?

Tested on PHP 5.6.4. 在PHP 5.6.4上测试过。

Reason for what I'm trying to do is the fact the search function is obviously more complex in my use case (not just a key indexing!), and after the result has been found, it's handy to work on results: the original array is nested at various levels. 我想要做的事情的原因是搜索功能在我的用例中显然更复杂(不仅仅是一个键索引!),并且在找到结果之后,它可以很方便地处理结果:原始数组嵌套在各个级别。

From the manual : 手册

Note: Unlike parameter passing, here you have to use & in both places - to indicate that you want to return by reference, not a copy, and to indicate that reference binding, rather than usual assignment, should be done for $myValue. 注意:与参数传递不同,这里你必须在两个地方使用& - 表示你想通过引用而不是副本返回,并指示应该为$ myValue完成引用绑定,而不是通常的赋值。

Your code just needs an extra ampersand (the reference "binding" one referred to above), as follows: 您的代码只需要额外的&符号(上面提到的引用“绑定”),如下所示:

$a =& search('b');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM