I'm reading the book PHP Objects Patterns and Practice 2, and i found a contradictory affermation regarding the use of clone keyword.
It says
class CopyMe {}
$first = new CopyMe();
$second = $first;
// PHP 4: $second and $first are 2 distinct objects
// PHP 5 plus: $second and $first refer to one object
An exemple, assuming that we are using PHP5
class Account
{
public $balance;
function __construct( $balance )
{
$this->balance = $balance;
}
}
class Person
{
private $name;
private $age;
private $id;
public $account;
function __construct( $name, $age, Account $account )
{
$this->name = $name;
$this->age = $age;
$this->account = $account;
}
function setId( $id )
{
$this->id = $id;
}
function __clone()
{
$this->id = 0;
}
}
$person = new Person( "bob", 44, new Account( 200 ) );
$person->setId( 343 );
$person2 = clone $person;
// give $person some money
$person->account->balance += 10;
// $person2 sees the credit too
print $person2->account->balance;
The problem of this approach obviously is that account is shared between the two objects, and this is not what we want.
So the book suggest this solution, adding this other beavior inside the __clone interceptor
function __clone()
{
$this->id = 0;
$this->account = clone $this->account; //<----My doubt there
}
I've not tryied it, but i suppose that it work fine
But as asserted at the beginning, clone keyword don't create a reference to a same object? Why in this exemple is treaty such it create a completely independent object?