【发布时间】:2015-12-18 14:02:21
【问题描述】:
我正在使用How to get random value out of an array 中的an answer 编写一个从数组中返回随机项的函数。我将其修改为pass by reference 和return a reference。
不幸的是,它似乎不起作用。对返回对象的任何修改都不会持续存在。我做错了什么?
如果有什么不同,我正在使用 PHP 5.4(不要问)。
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。
【问题讨论】:
-
客户需求!我只能以多种方式多次告诉他们,使用 5.4 是一个糟糕的主意。
-
我知道,你说不要问,所以我当然不得不问。
-
可能客户会回复scary graphs。
-
你为什么使用引用?你只是想从
$companies返回一个随机数组吗? -
@bishop 需要更多红色!我实际上向他们展示了这一点,他们还没有改变主意。
标签: php pass-by-reference