PHP中有没有办法返回对数组中元素的引用?
function ref(&$array, &$ref) { $ref = $array[1]; }
$array = array(00, 11, 22, 33, 44, 55, 66, 77, 88, 99);
ref($array, $ref);
$ref = 'xxxxxxxxxx';
var_dump($ref);
var_dump($array);
我希望$ array会被改变,如下面的代码所示:
$array = array(00, 11, 22, 33, 44, 55, 66, 77, 88, 99);
$ref = &$array[1];
$ref = 'xxxxxxxxxx';
var_dump($ref);
var_dump($array);
答案 0 :(得分:14)
我找到了两种方法来返回对数组元素的引用:
function & ref(&$array)
{
return $array[1];
}
$array = array(00, 11, 22, 33, 44, 55, 66, 77, 88, 99);
$ref =& ref($array);
$ref = 'xxxxxxxxx';
var_dump($ref);
var_dump($array);
function ref(&$array, &$ref = array())
{
$ref = array();
$ref[] = &$array[1];
}
$array = array(00, 11, 22, 33, 44, 55, 66, 77, 88, 99);
ref($array, $ref);
$ref[0] = 'xxxxxxxxx';
var_dump($ref);
var_dump($array);