note 87066 modified in language.oop5.cloning by cmb
| From: | cmb@php.net | Date: | Sun, 10 Jul 2016 20:19:17 +0000 |
| Subject: | note 87066 modified in language.oop5.cloning by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-205957@lists.php.net to get a copy of this message | ||
Want deep cloning without too much hassle?
<?php
function __clone() {
foreach($this as $key => $val) {
if(is_object($val)||(is_array($val))){
$this->{$key} = unserialize(serialize($val));
}
}
}
?>
That will insure any object, or array that may potentially contain objects, will get cloned without
using recursion or other support methods.
[EDIT BY danbrown AT php DOT net: An almost exact function was contributed on 02-DEC-2008-10:18 by
(david ashe AT metabin):
<?php
function __clone(){
foreach($this as $name => $value){
if(gettype($value)=='object'){
$this->$name= clone($this->$name);
}
}
}
?>
Giving credit where it's due. ~DPB]
[EDIT BY cmb AT php DOT net: the latter function fails to make deep copies of object arrays, and
might end up with infinite recursion.]
--was--
Want deep cloning without too much hassle?
<?php
function __clone() {
foreach($this as $key => $val) {
if(is_object($val)||(is_array($val))){
$this->{$key} = unserialize(serialize($val));
}
}
}
?>
That will insure any object, or array that may potentially contain objects, will get cloned without
using recursion or other support methods.
[EDIT BY danbrown AT php DOT net: An almost exact function was contributed on 02-DEC-2008-10:18 by
(david ashe AT metabin):
<?php
function __clone(){
foreach($this as $name => $value){
if(gettype($value)=='object'){
$this->$name= clone($this->$name);
}
}
}
?>
Giving credit where it's due. ~DPB]
http://php.net/manual/en/language.oop5.cloning.php