25.09.2014 Views

ZEND PHP 5 Certification STUDY GUIDE

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

118 ” Object Oriented Programming in <strong>PHP</strong><br />

Constructors<br />

<strong>PHP</strong> 5 introduces the concept of the unified constructor and, along with it, a new<br />

destructor for objects. The constructor and destructor are special class methods that<br />

are called, as their names suggest, on object creation and destruction, respectively.<br />

Constructors are useful for initializing an object’s properties, or for performing startup<br />

procedures, such as, for example, connecting to a database, or opening a remote<br />

file.<br />

The concept of the constructor is, of course, not new to <strong>PHP</strong> 5. In <strong>PHP</strong> 4, it was<br />

possible to define a class method whose name was the same as the class itself; <strong>PHP</strong><br />

would then consider this method to be the class’ constructor and call it whenever<br />

a new instance of the class was created. This approach had several drawbacks—for<br />

example, if you decided to rename your class, you would also have to rename your<br />

constructor.<br />

To avoid these problems, <strong>PHP</strong> 5 now uses the magic __construct() method as the<br />

constructor for any class regardless of the class’ name. This greatly simplify things,<br />

and provides you with a standard mechanism to recognize and call constructors in a<br />

consistent manner:<br />

class foo {<br />

function __construct()<br />

{<br />

echo __METHOD__;<br />

}<br />

function foo()<br />

{<br />

// <strong>PHP</strong> 4 style constructor<br />

}<br />

}<br />

Licensed to 482634 - Amber Barrow (itsadmin@deakin.edu.au)<br />

new foo();<br />

This example will display foo::__construct (the __METHOD__ constant is replaced at<br />

compilation time with the name of the current class method). Note that, if the<br />

__construct() method is not found, <strong>PHP</strong> will look for the old <strong>PHP</strong> 4-style constructor<br />

(foo) and call that instead.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!