Assign by reference bug

纵饮孤独 提交于 2019-11-28 06:55:18

This is explained over at the PHP manual (even if you have to spend more time than you should have to in order to find it), specifically over at http://php.net/manual/en/language.types.array.php#104064

The "shared" data stays shared, with the initial assignment just acting as an alias. It's not until you start manipulating the arrays with independent operations like ...[] = ... that the intepreter starts to treat them as divergent lists, and even then the shared data stays shared so you can have two arrays with a shared first n elements but divergent subsequent data.

For a true "copy by value" for one array to another, you pretty much end up doing something like

$arr2 = array();
foreach($arr1 as $val) {
  $arr2[] = $val;
}

or

$arr2 = array();
for($i=count($arr1)-1; $i>-1; $i--) {
  $arr2[$i] = $arr[$i];
}

(using reverse looping mostly because not enough people remember that's a thing you can do, and is more efficient than a forward loop =)

You'd imagine there'd be an array_copy function or something to help deal with the array copy quirk, but there just doesn't seem to be one. It's odd, but one of those "the state of PHP" things. A choice was made in the past, PHP's lived with that choice for quite a few years as a result, so it's just "one of those things". Unfortunately!

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!