PHP5: inheritance and overriding

example of inheritance

figure -> rectangle -> square figure -> triangle

overriding:
methods overriding: “rectangle” and “triangle” override getArea() method (declared in the superclass abstract “figure”)
to override a method you MUST declare it with the same signature (name + number + arguments sequence)

superclass method calling:
figure declare a method to get area and a contructor, overridden in the class “square”


//abstract
abstract class figure
{

private $priv;
protected
$w, $h;
protected
$prot;
public
$pub;

public function __construct($w, $h) {
$this->w = $w; $this->h = $h;
}
abstract public function getArea();

}

class triangle extends figure
{

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

}

class rectangle extends figure
{

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

}

class square extends rectangle
{

//constructor . overriding ??
public function __construct($w){
//call superclass ctor
parent::__construct($w, $w);
}

}

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

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

$s = new square(11);
print
$s->getArea(); //121