Class Intermediates

The topics in the previous section covered the limit of PHP 4’s object-oriented abilities. This section introduces a few concepts new to PHP 5: interfaces, type hinting, and static methods and properties.


In object-oriented programming, objects must work together. Therefore, you should be able to require a class (or more than one class) to implement methods that are necessary for the class to interact properly in your system.

For instance, an e-commerce application needs to know a certain set of information about every item up for sale. These items may be represented as different classes: Book, CD, DVD, etc. However, you need to know that your application can find the name, price, and inventory number of each object, regardless of its type.

The mechanism for forcing classes to support the same set of methods is called an interface. Defining an interface is similar to defining a class:

interface Sellable {
    public function getName( );
    public function getPrice( );
    public function getID( );

Instead of using the keyword class, an interface uses the keyword interface. Inside the interface, define your method prototypes, but don’t provide an implementation.

This creates an interface named Sellable. Any class that’s Sellable must implement the three methods listed in the interface: getName( ), getPrice( ), and getID( ).

When a class supports all the methods in the interface, it’s called implementing the interface. You agree to implement an interface in your class ...

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.