Abstract Classes.php

Jul 02, 2009 Author: City Hall

Yet another new feature added to PHP 5 is that of Interfaces and Abstract classes. These are both used to create a series of constraints on the base design of a group of classes. An abstract class essentially defines the basic skeleton of a specific type of encapsulated entity—for example, you can use an abstract class to define the basic concept of “car” as having two doors, a lock and a method that locks or unlocks the doors. Abstract classes cannot be used directly, but they must be extended so that the descendent class provides a full complement of methods. For example:

abstract class DataStore_Adapter {
private $id;
abstract function insert();
abstract function update();
public function save()
{
if (!is_null($this->id)) {$this->update();
}
 else {$this->insert();
}
}
}
class PDO_DataStore_Adapter extends DataStore_Adapter {
public __construct($dsn)
{
// ...
}
function insert()
{
// ...
}
function update()
{
// ...
}
}

IMPORTANT:You must declare a class as abstract so long as it has (or inherits without providing a body) at least one abstract method.

As you can see, in this example we define a class called DataStore_Adapter and declare two abstract methods called insert() and update(). Note how these methods don’t actually have a body—that’s one of the requirements of abstract classes—and how the class itself must be declared as abstract in order for the compiler to satisfy the parser’s syntactic requirements. We then extend DataStore_Adapter into PDO_DataStore_Adapter, which is no longer abstract because we have now provided a body for both insert() and update().


views 3185
  1. Add New Comment