开发者

PHP unreference

开发者 https://www.devze.com 2023-02-09 05:47 出处:网络
Lets say i have this code: $val = 1; $arr = Array(); $arr[\'val\'] =& $val; $val = 2; echo $arr[\'val\']; This will print out 2, because $val was passed to $arr by reference.

Lets say i have this code:

$val = 1;
$arr = Array();
$arr['val'] =& $val;
$val = 2;
echo $arr['val'];

This will print out 2, because $val was passed to $arr by reference.

My question is : if i passed a value to an array by reference, is there a way to remove that reference later on, making it a simple copied value ? To make it clearer, i would like something like this:

$val = 1;
$arr = Array();
$arr['val'] =& $val;

$arr['val'] = clone $arr['val']; 
// Or better yet:
$arr = clone $arr;

$val = 2;
echo $arr['val'];

And this should print out 1 (because the array was cloned, before the referenced variable changed). Howerver, clone does not work with arrays, it only works with objects.

Any ideas? I really have n开发者_如何学Co clue how to do this. I tried writing a recursive copy function, but that didn't work.


You could unset the index and then reassign by-value instead of by reference.

unset($arr['val']);
$arr['val'] = $val;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号