Inheritance
Inheritance

When we inherit base class member into the derived class is called inheritance. Means after inheritance we can access base class member in the derived class. For inheritance we use extends keyword in the derived class.

Note :- we can inherit only protected member and public member. private member can not be inherit.

Example 1:- In this we create two class name as base and derived. we inherit the base class member into the derived class.

<?php
class base
{
private $num1;
protected $num2;
public $num3;
function input1($x)
{
$this->num1=$x;
}
function output1()
{
echo "private member of base class ".$this->num1." "."<br>";
}
}

class derived extends base
{
public $num4;
function input2($p,$r,$s)
{
$this->num2=$p;
$this->num3=$r;
$this->num4=$s;
}
function output2()
{
echo "protected member of base class ".$this->num2." "."<br>";
echo "public member of base class ".$this->num3." "."<br>";
echo "public member derived class ".$this->num4." "."<br>";
}
}

$obj1=new base();
$obj2=new derived();

$obj1->input1(4);
$obj2->input2(6,7,8);

$obj1->output1();
$obj2->output2();
?>

Output:-
private member of base class 4
protected member of base class 6
public member of base class 7
public member derived class 8

Inheritance - method overriding

When the function of the base class and derived class are same. same means same function name, sam signature and same access specifier.

For example

class base {
public function test(){
--- your code here ---
}
}

class derived1 extends base {
public function test(){
--- your code here ---
}
}

class derived1 extends base {
public function test(){
--- your code here ---
}
}

Note:- function test same in all class. this is called method overridding

Example 2:- To use of method overriding

<?php
class base {
    public function test() {
        echo "This function inside base class";
    }
}
 
class derived1 extends base {
    public function test() {
        echo "This function inside derived1 class";
    }
}
 
class derived2 extends base {
    public function test() {
        echo "This function inside derived2 class";
    }
}
 
$obj1 = new derived1();
$obj2 = new derived2();
 
$obj1->test();
echo "\n";
$obj2->test();
?>

Example 3:- To use of parent keyword

<?php
class base {
    public function show() {
        echo "This is base class function\n";
    }
}
 
class derived extends base{
    public function show() {
        parent::show();
        echo "This is derived class function\n";
    }
}
 
$c = new derived();
$c->show();
?>

Output:-
This is base class function This is derived class function


Previous
Next