Magical Methods

PHP 5 has a few methods that are implicitly invoked behind the scenes. You’ve already seen two, _ _construct( ) and _ _destruct( ), but these are not the only special methods in PHP 5.

There are seven special methods, and they are as follows:

_ _construct( )

Called when instantiating an object

_ _destruct( )

Called when deleting an object

_ _get( )

Called when reading from a nonexistent property

_ _set( )

Called when writing to a nonexistent property

_ _call( )

Called when invoking a nonexistent method

_ _toString( )

Called when printing an object

_ _clone( )

Called when cloning an object

These methods are easy to spot, since they all begin with two underscores (_ _).

_ _get( ) and _ _set( )

You’ve read a lot about the benefits of encapsulation and why your classes must have accessor methods. Writing these methods, however, induces numbness as you repeatedly create methods for each property in your class. PHP 5 has two special methods, _ _set( ) and _ _get( ), to ease your pain.

In PHP 4, the only way to handle accessors is to write your own set of methods for each property. By convention, these methods often begin with the word set and end with the property name. So, to set a Person’s name, you call setName( ).

Using PHP 4 and accessors, the code looks like this:

class Person { var $name; var $email; function setName($name) { $this->name = $name; } function getName( ) { return $this->name; } } $rasmus = new Person; $rasmus->setName('Rasmus Lerdorf'); print $ramsus->getName( ...

Get Upgrading to PHP 5 now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.