abstract classes in php5

abstract class:

  • you CANNOT instantiate it, you can ONLY INHERIT it !
  • some methods (at least one) are abstract and the subclass which inherit from it must implement its abstract methods (same visibility, name and arguments)
  • note: the subclass can access all the protected (and public) methods and members (NOT the private ones) of the superclass !

simple explanatory example:


//abstract
abstract class figure
{

//width and height
protected $w, $h; //or public. NOT private !!
public function __construct($w, $h){
$this->w = $w;
$this->h = $h;
}
//must override
abstract public function getArea();

}

class rectangle extends figure
{

//$l, $w are inherited because are protected
public function getArea() { return $this->w*$this->h; }

}

class triangle extends figure
{

public function getArea() { return $this->w*$this->h/2; }

}

//instantation
$s = new rectangle(10,20);
print
$s->getArea(); //200

$r = new triangle(10,20);
print
$r->getArea(); //100