Inheritance in PHP


Prev Tutorial Next Tutorial

Inheritance in PHP

Inheritance is one of the most important aspects of OOP. It allows a class to inherit members from another class. When a class is defined by inheriting existing function of a parent class then it is called Inheritance. Here child class will inherit all or few member functions and variables of a parent class.

For inherit one class into another class use extends keyword. In any language inheritance is used for reuse all ready written code in project.

Syntax

<?php

class A 
 {
   // more code here
 }

class B extends A 
 {
   // more code here
 }

class C extends B 
 {
   // more code here
 }

$obj1 = new A();  // no problems
$obj2 = new B(); // no problems
$obj3 = new C(); // still no problems

?>

Example of Inheritance in PHP

<?php

class Foo
{
    public function printItem($string)
    {
        echo 'Foo: ' . $string . PHP_EOL;
    }
    
    public function printPHP()
    {
        echo 'PHP is great.' . PHP_EOL;
    }
}

class Bar extends Foo
{
    public function printItem($string)
    {
        echo 'Bar: ' . $string . PHP_EOL;
    }
}

$foo = new Foo();
$bar = new Bar();
$foo->printItem('baz'); // Output: 'Foo: baz'
$foo->printPHP();       // Output: 'PHP is great' 
$bar->printItem('baz'); // Output: 'Bar: baz'
$bar->printPHP();       // Output: 'PHP is great'

?>

Output

Foo: baz PHP is great. Bar: baz PHP is great.

Prev Tutorial Next Tutorial

Advertisements




Download Projects