PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1

CHAPTER 4 ■ ADVANCED FEATURES


function __clone() {


$this->id = 0;
}
}


When clone is invoked on a Person object, a new shallow copy is made, and its clone() method is
invoked. This means that anything I do in
clone() overwrites the default copy I already made. In this
case, I ensure that the copied object’s $id property is set to zero.


$person = new Person( "bob", 44 );
$person->setId( 343 );
$person2 = clone $person;
// $person2 :
// name: bob
// age: 44
// id: 0.


A shallow copy ensures that primitive properties are copied from the old object to the new. Object
properties, though, are copied by reference, which may not be what you want or expect when cloning an
object. Say that I give the Person object an Account object property. This object holds a balance that I
want copied to the cloned object. What I don’t want, though, is for both Person objects to hold
references to the same account.


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 );

Free download pdf