Inheritance in PHP, is inheriting a class with another class, a class which is inherited called parent class and which inherits is called child class. In inheritance, child class uses (inherits) all parents class, public and protected data members and member functions. Private members cannot be inherited.
Also Called | |
---|---|
Parent class | Base, Super class |
Child class | Derived, Subclass |
Advantages of Inheritance
Inheritance allows to reuse code of a class in another class.
Example
<?php
class MyParent{
public $parentname;
function setParentName($n){
$this->parentname = $n;
}
}
class child1 extends MyParent{
public $name;
function setChildName($n){
$this->name = $n;
}
}
$obj = new child1();
//Calling Parent class function with child class object
$obj->setParentName('PHP');
//Calling child class function with child class object itself
$obj->setChildName('Inheritance');
?>