[英]PHP append array to array reference
I have a function which return reference to an array (globals are used for simplicity, actually these arrays are elements of some big tree structure): 我有一个函数,该函数返回对数组的引用(为简单起见,使用了全局变量,实际上这些数组是某些大树结构的元素):
$array1;
$array2;
function &foo($arg){
//deduce from $arg reference to which array should be returned
if(...) {
global $array1;
return $array1;
} else {
global $array2;
return $array2;
}
}
Then I need to append another array to the one returned with this function (so that initial array was changed): 然后,我需要向此函数返回的数组追加另一个数组(以便更改初始数组):
$arrayToAppend = array('a','b');
$arrayToChange = &foo($arg);
$arrayToChange = array_merge($arrayToChange, $arrayToAppend);
Is it correct syntax for what I want to do? 我要执行的语法正确吗? Does it change referenced array?
它会改变引用数组吗? Are there any pitfalls I should know?
我应该知道什么陷阱吗? (pitfalls about reference stuff, not about merging assosiative arrays etc.)
(有关参考资料的陷阱,而不是与合并关联数组有关的陷阱)
You are mixing things up. 您正在混淆。 You should only use & in front of a parameter in your function (if the parameter is a simple type, so no object) and you want the content of that parameter to change.
您仅应在函数中的参数前面使用&(如果参数是简单类型,因此没有对象),并且希望该参数的内容发生变化。
Example: 例:
<?php
$arrayToChange = array('a', 'b');
$arrayToAppend = array('c', 'd');
mergeArrays($arrayToChange, $arrayToAppend);
// $arrayToChange will now contain 'a', 'b', 'c', 'd'
function mergeArrays(& $array, $arrayToAppend)
{
$array = array_merge($array, $arrayToAppend);
}
//Note: This is not the way you should do it.
//A function best returns a result.
//This just illustrates how you can change the content of a parameter
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.