传递/返回对对象的引用 + 更改对象不起作用 [英] Passing/Returning references to object + changing object is not working
问题描述
我正在使用 一个答案来自如何从数组中获取随机值 编写一个从数组中返回随机项的函数.我将其修改为 pass by reference 和 返回引用.
I am using an answer from How to get random value out of an array to write a function that returns a random item from the array. I modified it to pass by reference and return a reference.
不幸的是,它似乎不起作用.对返回对象的任何修改都不会保留.我做错了什么?
Unfortunately, it doesn't appear to work. Any modifications to the returned object do not persist. What am I doing wrong?
我使用的是 PHP 5.4(不要问).
I'm on PHP 5.4 if that makes a difference (Don't ask).
function &random_value(&$array, $default=null)
{
$k = mt_rand(0, count($array) - 1);
$return = isset($array[$k])? $array[$k]: $default;
return $return;
}
用法...
$companies = array();
$companies[] = array("name" => "Acme Co", "employees"=> array( "John", "Jane" ));
$companies[] = array("name" => "Inotech", "employees"=> array( "Bill", "Michael" ));
$x = &random_value($companies);
$x["employees"][] = "Donald";
var_dump($companies);
输出...
array(2) {
[0] =>
array(2) {
'name' =>
string(7) "Acme Co"
'employees' =>
array(2) {
[0] =>
string(4) "John"
[1] =>
string(4) "Jane"
}
}
[1] =>
array(2) {
'name' =>
string(7) "Inotech"
'employees' =>
array(2) {
[0] =>
string(4) "Bill"
[1] =>
string(7) "Michael"
}
}
}
我什至复制并粘贴了文档中的示例,但这些示例都不起作用.他们都输出null
.
I even copied and pasted the examples from the documentation and none of those worked either. They all output null
.
推荐答案
三元运算符会创建一个隐式副本,这会破坏引用链.使用明确的if... else
:
The ternary operator creates an implicit copy, which breaks the reference chain. Use an explicit if... else
:
function &random_value(&$array, $default=null)
{
$k = mt_rand(0, count($array) - 1);
if (isset($array[$k])) {
return $array[$k];
} else {
return $default;
}
}
至于原因,文档现在说明:
注意:请注意,三元运算符是一个表达式,它的计算结果不是变量,而是表达式的结果.了解是否要通过引用返回变量很重要.语句返回 $var == 42 ?$a : $b;因此,在按引用返回的函数中将不起作用,并且在更高的 PHP 版本中会发出警告.
Note: Please note that the ternary operator is an expression, and that it doesn't evaluate to a variable, but to the result of an expression. This is important to know if you want to return a variable by reference. The statement return $var == 42 ? $a : $b; in a return-by-reference function will therefore not work and a warning is issued in later PHP versions.
另请参阅此错误,其中三元运算符实际上通过引用返回foreach
上下文,当它不应该时.
See also this bug where the ternary operator actually returns by reference in a foreach
context, when it shouldn't.
这篇关于传递/返回对对象的引用 + 更改对象不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!