PHP 5: Interfaces

Interfaces are a way of adding the definition of extra methods onto a class to force it to conform to a particular pattern. An interface consists entirely of methods with empty bodies i.e. abstract methods:

interface Saveable()
{
 public function save();
}

Classes implement interfaces as a way of guaranteeing that they will allow a set of operations as specified by the interface. E.g.

abstract class User implements Saveable
{
 /*
  Previous code for User here
 */
 public function save()
 {
  //Code in here for saving to disk
 }
} 

Interfaces are useful primarily to help document and constrain code, especially when used with class hinting (see next section). A class may implement more than one interface, separated by a comma e.g.

class User implements Saveable, Cacheable 

Advanced uses of Interfaces allows the treatment of objects as arrays (by implementing Iterator, ArrayAggregator and a number of Standard PHP Library interfaces).

Next section: Class hinting

Leave a Reply

Your email address will not be published. Required fields are marked *