25.09.2014 Views

ZEND PHP 5 Certification STUDY GUIDE

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

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

Determining An Object’s Class<br />

It is often convenient to be able to determine whether a given object is an instance<br />

of a particular class, or whether it implements a specific interface. This can be done<br />

by using the instanceof operator:<br />

if ($obj instanceof MyClass) {<br />

echo "\$obj is an instance of MyClass";<br />

}<br />

Naturally, instanceof allows you to inspect all of the ancestor classes of your object,<br />

as well as any interfaces.<br />

Exceptions<br />

Even though they have been a staple of object-oriented programming for years, exceptions<br />

have only recently become part of the <strong>PHP</strong> arsenal. Exceptions provide an<br />

error control mechanism that is more fine-grained than traditional <strong>PHP</strong> fault handling,<br />

and that allows for a much greater degree of control.<br />

There are several key differences between “regular” <strong>PHP</strong> errors and exceptions:<br />

• Exceptions are objects, created (or “thrown”) when an error occurs<br />

• Exceptions can be handled at different points in a script’s execution, and different<br />

types of exceptions can be handled by separate portions of a script’s<br />

code<br />

• All unhandled exceptions are fatal<br />

• Exceptions can be thrown from the __construct method on failure<br />

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

• Exceptions change the flow of the application<br />

The Basic Exception Class<br />

As we mentioned in the previous paragraph, exceptions are objects that must be<br />

direct or indirect (for example through inheritance) instances of the Exception base<br />

class. The latter is built into <strong>PHP</strong> itself, and is declared as follows:

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

Saved successfully!

Ooh no, something went wrong!