本文介绍了如何把一个对象的副本到PHP数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图对象添加到PHP数组,但它没有工作,尝试2种方法:
I tried to add objects into array in PHP but it didn't work, tried 2 methods:
1
$obj->var1 = 'string1';
$obj->var2 = 'string1';
$arr[] = $obj;
$obj->var1 = 'string2';
$obj->var2 = 'string2';
$arr[] = $obj;
2
$obj->var1 = 'string1';
$obj->var2 = 'string1';
array_push($arr,$obj);
$obj->var1 = 'string2';
$obj->var2 = 'string2';
array_push($arr,$obj);
这两种方法都将增加最新的对象到整个磁盘阵列。似乎对象被添加到由参考阵列。有没有办法通过值他们加入到数组?
Both methods will add the latest object into entire array. Seems that object is added to the array by reference. Is there a way to add they into array by value ?
推荐答案
对象总是通过引用在PHP 5或更高版本通过。如果你想要一个副本,您可以使用克隆算
Objects are always passed by reference in php 5 or later. If you want a copy, you can use the clone operator
$obj = new MyClass;
$arr[] = clone $obj;
这篇关于如何把一个对象的副本到PHP数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!