Wednesday, December 9, 2009

Understanding Class Inheritance

There are many benefits of inheritance with PHP, the most common is simplifying and reducing instances of redundant code. Class inheritance may sound complicated, but think of it this way. Consider a tree. A tree is made up of many parts, such as the roots that reside in the ground, the trunk, bark, branches, leaves, etc. Essentially inheritance is a connection between a child and its parent.

class Car{
var $wheels=4;
var $doors=4;

function wheelsdoors(){
return $this->wheels + $this->doors;
}
}

class CompactCar extends Car{
var $doors=2;
function wheelsdoors(){
return $this->wheels + $this->doors+ 100;
}
}

$car1 = new Car();
$car2 = new CompactCar();

echo $car1->wheels . "
";
echo $car1->doors . "
";
echo $car1->wheelsdoors() . "
";
echo "
";
echo $car2->wheels . "
";
echo $car2->doors . "
";
echo $car2->wheelsdoors() . "
";

echo "Car parents:".get_parent_class('Car')."
";
echo "CompactCar parents:".get_parent_class('CompactCar')."
";
echo "
";
echo is_subclass_of('Car','Car')? 'true' : 'false';
echo "
";
echo is_subclass_of('CompactCar','Car')? 'true' : 'false';
echo "
";
echo is_subclass_of('Car','CompactCar')? 'true' : 'false';


?>

Source: www.webreference.com

No comments:

Post a Comment

I just got my #domain @BigRock. Get upto 25% off with my personalized coupon link Get upto 25% off