2082 10

CSC329 ยท 2082 ยท 5 marks

Write a PHP program to demonstrate the concept of inheritance.

Write a PHP program to demonstrate the concept of inheritance. [5]

Web TechnologyChapter 6: Server Side Scripting using PHPCreating Class and Objects

Quick answer

Inheritance is an OOP concept where a child class (derived class) acquires the properties and methods of a parent class (base class) using the extends keyword. This promotes code reusability.

PHP Program to Demonstrate Inheritance

Concept of Inheritance in PHP


PHP Program

<?php

// Parent Class (Base Class)
class Animal {
    public $name;
    public $color;

    // Constructor of Parent Class
    public function __construct($name, $color) {
        $this->name  = $name;
        $this->color = $color;
    }

    // Method in Parent Class
    public function eat() {
        echo $this->name . " eats food. ";
    }

    public function display() {
        echo "Name  : " . $this->name  . " ";
        echo "Color : " . $this->color . " ";
    }
}

// Child Class (Derived Class) - inherits from Animal
class Dog extends Animal {
    public $breed;

    // Constructor of Child Class
    public function __construct($name, $color, $breed) {
        // Call parent constructor using parent keyword
        parent::__construct($name, $color);
        $this->breed = $breed;
    }

    // Method specific to Child Class
    public function bark() {
        echo $this->name . " says: Woof! Woof! ";
    }

    // Overriding parent method (Method Overriding)
    public function display() {
        parent::display();
        echo "Breed : " . $this->breed . " ";
    }
}

// Creating object of Parent Class
echo "<b>--- Animal Object ---</b> ";
$animal = new Animal("Cat", "White");
$animal->display();
$animal->eat();

echo " ";

// Creating object of Child Class
echo "<b>--- Dog Object (Child Class) ---</b> ";
$dog = new Dog("Tommy", "Brown", "Labrador");
$dog->display();   // Calls overridden display()
$dog->eat();       // Inherited from Animal
$dog->bark();      // Own method of Dog

?>

Output

--- Animal Object ---
Name  : Cat
Color : White
Cat eats food.

--- Dog Object (Child Class) ---
Name  : Tommy
Color : Brown
Breed : Labrador
Tommy eats food.
Tommy says: Woof! Woof!

Key Points Demonstrated

ConceptDescription
extendsUsed to inherit parent class into child class
parent::__construct()Calls the constructor of the parent class
Inherited methodeat() is defined in Animal but used by Dog
Method Overridingdisplay() is redefined in Dog class
Child-specific methodbark() belongs only to Dog class

Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.