I want to do this:
class T
{
public $a;
public $b;
public function __construct()
{
$this->a = new P;
$this->b = clone $this->a;
}
}
class P
{
public $name ="Chandler";
public function __clone()
{
$this->name = & $that->name;
}
}
$tour = new T;
$tour->a->name = "Muriel";
?>
But after this, $tour->b->name will be NULL, why ?
How can I make the clone name property reference to the parent object name property, so when I change the parent object name, the cloned object name will change accordingly ?
$thatdoesn’t exist in the__clonefunction as said in George Schlossnagle: Advanced PHP Programming book… It gave me a couple of weeks headache…So, you can do this with a simple trick in the constructor (in class
P); make the variable reference to himself:this works in PHP 5.3.6. I did not test it in other versions.
So when you do
$tour->a->name = "Muriel";, then$tour->b->namewill be “Muriel” too!