Saturday, March 28, 2009

Class inheritance example in Php

With a simple example you can understand the inheritance concept. Think about Human class. All human have mouth, can eat, have nose etc. If you say Man class, all Man subclass inherits the characters of Human parent class plus has his own characteristics. Similarly female subclass inherits Man parent class.

Inheritance indicates the relationship between classed. If we have a generic class and another class inherits the generic class then the derived class inherit the attributes and behaviors from their parent classes, and can introduce their own. The derived class is the more specialized version of the parent class.

With the extends keyword in declaration subclass is defined. Note that a subclass can only inherits one base class. If the parent class is not defined as final then inside the subclass inherited methods and attributes can be overridden. To access the parent class methods and attributes parent:: keyword can be used.

Below is the class inheritance example in php.

<?php
class BaseClass{
function display(){
echo "This is base class.";
echo "<br />";
}
}

class DerivedClass extends baseClass{
function display(){
echo "This is derived class.";
echo "<br />";
parent::display();
}
}
$derivedclass=new DerivedClass();
$derivedclass->display();
?>


And the output is,
This is derived class.
This is base class.

Related Documents

http://arjudba.blogspot.com/2009/03/class-concepts-and-usage-syntax-in-php.html

No comments:

Post a Comment