Showing posts with label inheritance. Show all posts
Showing posts with label inheritance. Show all posts

Thursday, June 4, 2009

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

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
 

PHP and tips|PHP