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

This entry was posted in PHP, Programming. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s