For Programmers: Free Programming Magazines  


Home > Archive > PHP Language > May 2006 > Problem with object cloning in PHP5









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author Problem with object cloning in PHP5
AmicoFritz

2006-05-12, 6:58 pm

When I clone an istance of System class I want to clone all SubSystem
istances in $subsystems array too, so I tryed with this code:

class System {
public $name;
public $subsystems = array();

function __construct($name){
$this->name = $name;
}

function __clone(){
foreach( $this->subsystems as $key => $item ){
$this->subsystems[$key] = clone($this->subsystems[$key]);
}
}
}

class SubSystem {
public $name;
public $type = 2;
public $skip_AP_search = false;

function __construct($name){
$this->name = $name;
}
}



But when I clone...


--- var_dump($orig->subsystems);

array(1) {
[0]=>
&object(SubSystem)#12 (7) {
["name"]=>
string(4) "sub1"
["type"]=>
int(2)
["skip_AP_search"]=>
bool(false)
}
}

--- var_dump($copy->subsystems);

array(1) {
[0]=>
&object(SubSystem)#12 (7) {
["name"]=>
string(4) "sub1"
["type"]=>
int(2)
["skip_AP_search"]=>
bool(false)
}
}


So the istances in the arrays are the same :(

What's wrong?
Colin McKinnon

2006-05-12, 6:58 pm

AmicoFritz wrote:

> When I clone an istance of System class I want to clone all SubSystem
> istances in $subsystems array too, so I tryed with this code:


<snip>
>
> function __clone(){
> foreach( $this->subsystems as $key => $item ){
> $this->subsystems[$key] = clone($this->subsystems[$key]);
> }
> }


because you've replaced the thing refered to by '$this->subsystems[$key]'
with a clone of '$this->subsystems[$key]' - and that thing is currently
referenced by the arrays of both objects.

Off the top of my head, I'd try:

function __clone()
{
$new=array();
foreach( $this->subsystems as $key => $item ){
$new[$key]=clone($this->subsystems[$key]);
}
$this->subsystems=$new;
}

Or for an ugly fix, instead of $newObj = clone $oldObj,

$newObj=unserialize(serialize($oldObj));


HTH

C.
Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2009 codecomments.com