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.
Interfaces
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 ...
Get Upgrading to PHP 5 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.