Inheritance in PHP

Advertisements

Polymorphism in PHP Cookies in PHP

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.

Polymorphism in PHP Cookies in PHP

Google Advertisment

Buy This Ad Space @$20 per Month, Ad Size 600X200 Contact on: hitesh.xc@gmail.com or 9999595223

Magenet is best Adsense Alternative here we earn $2 for single link, Here we get links ads. Magenet

For Projects 9999595223

Google Advertisements


Buy Websites 9999595223

Buy College Projects with Documentation Contact on whatsapp 9999595223. Contact on: hitesh.xc@gmail.com or 9999595223 Try this Keyword C++ Programs

Advertisements