Inheritance in OOP PHP

Inheritance is a concept in object oriented programming. With the help of inheritance we can get all property and method of one class in another class. The class who inherit feature of another class known as child class.The class which is being inherited is know as parent class. With the help of inheritance you can increase re-usability of code. Here is some clarification about PHP inheritance – there is a lot of bad information on the net. PHP does support Multi-level inheritance. (I tested it using version 5.2.9). It does not support multiple inheritance. This means that you cannot have one class extend 2 other classes (see the extends keyword). However, you can have one class extend another, which extends another, and so on.

Example:

class A {
        // more code here
}

class B extends A {
        // more code here
}

class C extends B {
        // more code here
}


$someObj = new A();  // no problems
$someOtherObj = new B(); // no problems
$lastObj = new C(); // still no problems

?>

Inheritance Example

class Test
{
    public function printItem($var)
    {
        echo 'Parent class function'. $var;
    }
    
    public function printPHP($var)
    {
        echo 'PHP is great'.$var;
    }
}

class Testchild extends Test
{
    public function printItem($var)
    {
        echo 'Child class function.' .$var;
    }
}

$Test = new Test();
$Testchild = new Testchild();
$Test->printItem('baz'); // Output: 'Parent class function. baz'
$Test->printPHP('child function');       // Output: 'PHP is great' 
$Testchild->printItem('baz'); // Output: 'Child class function. baz'
$Testchild->printPHP();       // Output: 'PHP is great'

You can see in the above example we don’t created the function printPHP() for the child class but it still give us the output ‘PHP is great’ which we have created in the parent class. This is how Inheritance in OOP PHP work.

Read more OOP in PHP