PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1

CHAPTER 4 ■ ADVANCED FEATURES


Defining Destructor Methods


You have seen that the construct() method is automatically invoked when an object is instantiated.
PHP 5 also introduced the
destruct() method. This is invoked just before an object is garbage-
collected; that is, before it is expunged from memory. You can use this method to perform any final
cleaning up that might be necessary.
Imagine, for example, a class that saves itself to a database when so ordered. I could use the
__destruct() method to ensure that an instance saves its data when it is deleted.


class Person {
private $name;
private $age;
private $id;


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


function setId( $id ) {
$this->id = $id;
}


function __destruct() {
if (! empty( $this->id ) ) {
// save Person data
print "saving person\n";
}
}
}


The destruct() method is invoked whenever a Person object is removed from memory. This will
happen either when you call the unset() function with the object in question or when no further
references to the object exist in the process. So if I create and destroy a Person object, you can see the
destruct() method come into play.


$person = new Person( "bob", 44 );
$person->setId( 343 );
unset( $person );
// output:
// saving person


Although tricks like this are fun, it’s worth sounding a note of caution. call(), destruct(), and
their colleagues are sometimes called magic methods. As you will know if you have ever read a fantasy
novel, magic is not always a good thing. Magic is arbitrary and unexpected. Magic bends the rules. Magic
incurs hidden costs.
In the case of destruct(), for example, you can end up saddling clients with unwelcome surprises.
Think about the Person class—it performs a database write in its
destruct() method. Now imagine a
novice developer idly putting the Person class through its paces. He doesn’t spot the __destruct()
method and he sets about instantiating a set of Person objects. Passing values to the constructor, he
assigns the CEO’s secret and faintly obscene nickname to the $name property, and sets $age at 150. He
runs his test script a few times, trying out colorful name and age combinations.
The next morning, his manager asks him to step into a meeting room to explain why the database
contains insulting Person data. The moral? Do not trust magic.

Free download pdf