php如何真“拷贝”一个数组
本文翻译改编自:http://stackoverflow.com/questions/1532618/is-there-a-function-make-a-copy-of-a-php-array-to-another原文链接:http://www.tjwzjs.cn/news/knowledge/2012/1218/function-copy-a-array-to-another.html
问:“如何在php中实现数组的拷贝?php数组是基于值拷贝还是引用拷贝呢?”
谢谢 @jamcode 的提醒,我对原文理解犯了一个很大的错误,附原文:
Is there a function make a copy of a PHP array to another?
I have been burned a few times trying to copy PHP arrays. I want to copy an array defined inside an object to a global outside it.
在PHP中如何实现这种拷贝呢?
下面写一个简单的拷贝代码:
$a = array();
$b = $a;
$b['foo'] = 42;
var_dump($a);
当我们运行这段代码时,得到
array(0) {
}
可见,我们修改了B的值,但是A却没有相应的改变。于是我们换一段代码试试:
$a = new StdClass();
$b = $a;
$b->foo = 42;
var_dump($a);
此次的输出结果变成了:
object(stdClass)#1 (1) {
["foo"]=>
int(42)
}
ArrayObject 的行为虽然是一个数组,但是他确实是一个对象,它是通过传递引用实现赋值的。
页:
[1]