rss search

PHP Inheritance

line PHP Inheritance
interface hasArea {
	public function getArea();
}

class Rectangle implements hasArea {
	static $w;
	static $l;
	public function __construct($w, $l) {
		$this->w = $w;
		$this->l = $l;
	}

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

class Square extends Rectangle {
	public function setWidth($w) {
		parent::$w = $w;
	}

	public function setLength($l) {
		parent::$l = $l;
	}

	public function getArea() {
		return parent::$w * parent::$l;
	}

	public function getArea2() {
		return $this->w * $this->l;
	}
}

$rect = new Rectangle(10, 5);
print $rect->getArea();
print "";
$sqr = new Square(5, 5);
print $sqr->getArea();
print "";
print $sqr->getArea2();
print "";
$sqr->setWidth(10);
$sqr->setLength(10);
print $sqr->getArea();

/*
	Output:
	50
	0
	25
	100
*/

PHP supports inheritance and polymorphism. The above is one tiny example when I played around with it. If you see the output, you realize that setWidth and setLength would set the parent variable, in which is NOT set even I’ve instantiated Rectangle using $w and $l parameter on its constructor.


Leave a Reply

You must be logged in to post a comment.