Studyon Minte9.com
ZCE 5.3

Study

Interfaces & Abstract



	// Abstract - cannot be instantiated; signatures and implementations; pdo adapter; extended
	// Interfaces - specify an API that a class must implement; no body; implemented


Abstract and Interfaces are design to create a series of constrains.

Abstract class defines a basic skeleton, cannot be used directly.

<?php abstract class A { abstract function a(); public function b() { /* body */ } } class B extends A {} // Fatal error: Class B contains 1 abstract method // --- Look Here --- // // and must therefore be declared abstract or // implement the remaining methods (A::a)
 
<?php abstract class myAdapter { private $id; abstract function insert(); abstract function update(); public function save() { if (!is_null($this->id)) { $this->update(); } else { $this->insert(); } } } class PDO_myAdapter extends myAdapter{ public function __construct($dsn) { // ... } public function insertWrongName() { // ... } public function update() { // ... } // Fatal error: Class PDO_myAdapter contains 1 abstract method // --- Look Here --- // // and must therefore be declared abstract or implement the remaining methods // (myAdapter::insert) }
  Interfaces are used to specify an API that a class must implement; contain no body.
<?php interface myAdapter { public function insert(); public function update(); public function save(); public function foo($name=null); } class PDO_Adapter implements myAdapter { public function insert() { // ... } public function update() { // ... } public function save() { // ... } public function foo($name) { // must be $name=null // --- Look Here --- // // ... } // Fatal error: Declaration of PDO_Adapter::foo() // must be compatible with that of myAdapter::foo() }
  A class can only extend one parent class, but it can implement multiple interfaces.
<?php class PDO_Adapter extends PDO implements myAdapter, SeekableIterator { ... }
You can check if an object is an instance of a particular class.
<?php class foo {} $foo = new foo; if ($foo instanceof foo) { // true // --- Look Here --- // echo "Object $foo is an instance of MyClass"; }