O'Reilly logo

Upgrading to PHP 5 by Adam Trachtenberg

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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( ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required