PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1
CHAPTER 4 ■ ADVANCED FEATURES

$person2 = clone $person;


// give $person some money
$person->account->balance += 10;
// $person2 sees the credit too
print $person2->account->balance;


This gives the output:

210


$person holds a reference to an Account object that I have kept publicly accessible for the sake of
brevity (as you know, I would usually restrict access to a property, providing an accessor method if
necessary). When the clone is created, it holds a reference to the same Account object that $person
references. I demonstrate this by adding to the $person object’s Account and confirming the increased
balance via $person2.
If I do not want an object property to be shared after a clone operation then it is up to me to clone it
explicitly in the __clone() method:


function __clone() {
$this->id = 0;
$this->account = clone $this->account;
}


Defining String Values for Your Objects


Another Java-inspired feature introduced by PHP 5 was the __toString() method. Before PHP 5.2, when
you printed an object, it would resolve to a string like this:


class StringThing {}
$st = new StringThing();
print $st;


Object id #1


Since PHP 5.2, this code will produce an error like this:

PHP Catchable fatal error: Object of class StringThing could not be
converted to string in ...


By implementing a toString() method, you can control how your objects represent themselves
when printed.
toString() should be written to return a string value. The method is invoked
automatically when your object is passed to print or echo, and its return value is substituted. Here I add
a __toString() version to a minimal Person class:


class Person {
function getName() { return "Bob"; }

Free download pdf