What is Inheritance in PHP?

Every class has its own properties and methods. Suppose Class A & Class B has its own properties and methods. If Class B want to access Class A properties, here php oops introduce Inheritance concept. Through Php Inheritance many classes and objects relate to one another. The class which properties or methods will used in inheritance is called Base Class And which class is using this method or properties is called derived class.


Inheritance in PHP



If we can use more than one inheritance its called multilevel inheritance. please see below image for it.


multilevel inheritance


Example of Inheritance

The Tomato class is inherited from the Vegetable class.

This means that the Tomato class can use the public $name and $color properties as well as the public __construct() and intro() methods from the Fruit class because of inheritance.

The Tomato class also has its own method: message().

<!DOCTYPE html>

<html>

<body>

<?php

class Vegetable {

public $name;

public $color;

public function __construct($name, $color) {

$this->name = $name;

$this->color = $color;

}

public function intro() {

echo “{$this->name} is fruit and the color is {$this->color}.”;

}

}

// Strawberry is inherited from Fruit

class Tomato extends Vegetable {

public function message() {

echo “Am I a fruit or a Vegetable? “;

}

}

$tomato = new Tomato(“Tomato”, “red”);

$tomato->message();

$tomato->intro();

?>

</body>

</html>


Comments

Popular posts from this blog

 8 महत्वपूर्ण सफलता कारक ईवेंट की मार्केटिंग के - 8 Key Success Factors for Event Marketing

3 आसान चरण प्रभावी ई-मार्केटिंग योजना के लिए - 3 Easy Steps for Effective E-marketing Plan

इंटरनेट मार्केटिंग कि गलत कल्पनाए | Myths About Internet Marketing