Hy大家!
如何在函数中返回数组引用/指针?
例如:
$a=array('given'=>array());
function getRef(&$ref){
//adds a child element to the given reference/pointer
$ref['test']=array();
//doesn't return the current reference/pointer
return $ref['test'];
}
//out: Array ( [given] => Array ( [test] => Array ( ) ) )
$p=getRef($a['given']);
print_r($a);
//out: same as above
//expected: ( [given] => Array ( [test] => Array ([test2] => Array ( ) ) ) )
$p['test2']=array();
print_r($a);
谢谢!
答案 0 :(得分:1)
function &getRef(&$ref){
return $ref['test'];
通过在函数开头使用&符号,可以返回变量的refference,而不是值。
答案 1 :(得分:0)
也许是这样的:
$a=array('given'=>array());
function getRef(&$ref){
//adds a child element to the given reference/pointer
$ref['test']=array();
//doesn't return the current reference/pointer
return $ref['test'];
}
//out: Array ( [given] => Array ( [test] => Array ( ) ) )
$p=getRef($a['given']);
print_r($a);
//out: same as above
//expected: ( [given] => Array ( [test] => Array ([test2] => Array ( ) ) ) )
$p['given']['test']['test2']=array();
print_r($p);
答案 2 :(得分:0)
当您通过引用传递时,您在函数内部使用与外部相同的变量,并且您不会返回值。 PHP Manual - Passing by Reference
$a = array('given' => array());
function getRef(&$a)
{
$a['test']=array();
}
// this now has the nested array test.
getRef($a['given']);
print_r($a);
如果这是您的所有功能,那么我建议您正常设置这些嵌套数组。
$b = ['given' => ['test' => ['test2' => []]]];
print_r($b);