requestFirst
正在将参数数组的轻量级副本传递给requestSecond
您所期望的。但是由于原始参数包含对 的引用,$conf
因此副本也包含引用。因此,当您修改该特定元素时,更改也可以通过对$conf
变量的所有其他引用可见:
function requestSecond($param) {
$param['conf']++; // change to the int counter happens here
}
function requestFirst($params) {
$params['conf']++;
requestSecond($params);
echo $params['conf']; // change is visible here
}
$conf = 1;
requestFirst(array(
'conf' => &$conf,
));
echo $conf; // change also visible here
但是,$param
它本身仍然是 的副本,$params
对其所做的任何更改都不会在以下范围之外可见requestSecond
:
function requestSecond($param) {
$param['conf']++;
$param['foo'] = 'bar';
}
function requestFirst($params) {
$params['conf']++;
requestSecond($params);
echo (int)isset($params['foo']); // "0" -- change not visible
}
您甚至可以在增加数组后从数组中删除引用;对引用计数器的更改将保留,对数组的更改不会:
function requestSecond($param) {
$param['conf']++;
// remove the reference from the array -- this will only affect
// the local copy $param and nothing else
unset($param['conf']);
}
function requestFirst($params) {
$params['conf']++;
requestSecond($params);
echo $params['conf']; // 3
}