13.09.2016 Views

PHP and MySQL Web Development 4th Ed-tqw-_darksiderg

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

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

184 Chapter 6 Object-Oriented <strong>PHP</strong><br />

Using Per-Class Constants<br />

<strong>PHP</strong> allows for per-class constants.This constant can be used without your needing to<br />

instantiate the class, as in this example:<br />

<br />

You can access the per-class constant by using the :: operator to specify the class the<br />

constant belongs to, as done in this example.<br />

Implementing Static Methods<br />

<strong>PHP</strong> allows the use of the static keyword. It is applied to methods to allow them to be<br />

called without instantiating the class.This is the method equivalent of the per-class constant<br />

idea. For example, consider the Math class created in the preceding section.You could add a<br />

squared() function to it <strong>and</strong> invoke it without instantiating the class as follows:<br />

class Math<br />

{<br />

static function squared($input)<br />

{<br />

return $input*$input;<br />

}<br />

}<br />

echo Math::squared(8);<br />

Note that you cannot use the this keyword inside a static method because there may be<br />

no object instance to refer to.<br />

Checking Class Type <strong>and</strong> Type Hinting<br />

The instanceof keyword allows you to check the type of an object.You can check<br />

whether an object is an instance of a particular class, whether it inherits from a class, or<br />

whether it implements an interface.The instanceof keyword is effectively a conditional<br />

operator. For instance, with the previous examples in which you implemented class B as<br />

a subclass of class A, then<br />

($b instanceof B)<br />

would be true.<br />

($b instanceof A)<br />

would be true.<br />

($b instanceof Displayable) would be false.<br />

All these examples assume that A, B, <strong>and</strong> Displayable are in the current scope; otherwise,<br />

an error will be triggered.

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

Saved successfully!

Ooh no, something went wrong!