Home arrow PHP arrow Page 2 - Polymorphism, Design Patterns, and PHP Programming

Interfaces and Type Hints - PHP

Last week, we continued our discussion of the object-oriented features of PHP 5 by taking a first look at design patterns. This week, we will continue looking at design patterns, and examine polymorphism. This article, the third of four parts, is excerpted from chapter two of the book Advanced PHP Programming, written by George Schlossnagle (Sams; ISBN: 0672325616).

  1. Polymorphism, Design Patterns, and PHP Programming
  2. Interfaces and Type Hints
  3. The Factory Pattern
  4. The Singleton Pattern
By: Sams Publishing
Rating: starstarstarstarstar / 9
October 05, 2006

print this article



A key to successful delegation is to ensure that all classes that might be dispatched to are polymorphic. If you set as the $dbh parameter for the Weblog object a class that does not implement fetch_row(), a fatal error will be generated at runtime. Runtime error detection is hard enough, without having to manually ensure that all your objects implement all the requisite functions.

To help catch these sorts of errors at an earlier stage, PHP5 introduces the concept of interfaces. An interface is like a skeleton of a class. It defines any number of methods, but it provides no code for them—only a prototype, such as the arguments of the function. Here is a basic interface that specifies the methods needed for a database connection:

interface DB_Connection {
public function execute($query);
public function prepare($query);

Whereas you inherit from a class by extending it, with an interface, because there is no code defined, you simply agree to implement the functions it defines in the way it defines them.

For example, DB_Mysql implements all the function prototypes specified by DB_Connection, so you could declare it as follows:

class DB_Mysql implements DB_Connection {
/* class definition */

If you declare a class as implementing an interface when it in fact does not, you get a compile-time error. For example, say you create a class DB_Foo that implements neither method:

require "DB/Connection.inc";
class DB_Foo implements DB_Connection {}

Running this class generates the following error:

Fatal error: Class db_foo contains 2 abstract
methods and must be declared abstract (db connection::execute, db
connection:: prepare) in /Users/george/Advanced
PHP/examples/chapter-2/14.php on line 3

PHP does not support multiple inheritance. That is, a class cannot directly derive from more than one class. For example, the following is invalid syntax:

class A extends B, C {}

However, because an interface specifies only a prototype and not an implementation, a class can implement an arbitrary number of interfaces. This means that if you have two interfaces A and B, a class C can commit to implementing them both, as follows:

interface A {
public function abba();
interface B {
public function bar();
class C implements A, B {
public function abba()
// abba;
public function bar()
// bar;

An intermediate step between interfaces and classes is abstract classes. An abstract class can contain both fleshed-out methods (which are inherited) and abstract methods (which must be defined by inheritors). The following example shows an abstract class A, which fully implements the method abba() but defines bar() as an abstract:

abstract class A {
public function abba()
// abba
abstract public function bar();

Because bar() is not fully defined, it cannot be instantiated itself. It can be derived from, however, and as long as the deriving class implements all of A's abstract methods, it can then be instantiated. B extends A and implements bar(), meaning that it can be instantiated without issue:

class B {
public function bar()
$b = new B;

Because abstract classes actually implement some of their methods, they are considered classes from the point of view of inheritance. This means that a class can extend only a single abstract class.

Interfaces help prevent you from shooting yourself in the foot when you declare classes intended to be polymorphic, but they are only half the solution to preventing delegation errors. You also need to be able to ensure that a function that expects an object to implement a certain interface actually receives such an object.

You can, of course, perform this sort of computation directly in your code by manually checking an object's class with the is_a() function, as in this example:

function addDB($dbh) 
if(!is_a($dbh, "DB_Connection")) {
trigger_error("\$dbh is not a DB_Connection
object", E_USER_ERROR); } $this->dbh = $dbh; }

This method has two flaws:

  • It requires a lot of verbiage to simply check the type of a passed parameter.

  • More seriously, it is not a part of the prototype declaration for the function. This means that you cannot force this sort of parameter checking in classes that implement a given interface.

PHP5 addresses these deficiencies by introducing the possibility of type-checking/type hinting in function declarations and prototypes. To enable this feature for a function, you declare it as follows:

function addDB(DB_Connection $dbh)
$this->dbh = $dbh;

This function behaves exactly as the previous example, generating a fatal error if $dbh is not an instance of the DB_Connection class (either directly or via inheritance or interface implementation).

>>> More PHP Articles          >>> More By Sams Publishing

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates


Dev Shed Tutorial Topics: