Google News
logo
PHP program to Inheritance
Inheritance is an important feature of object-oriented programming, allowing a new class to be based on an existing class, inheriting its attributes and methods. In PHP, inheritance is achieved using the `extends` keyword.

Here's an example program that demonstrates inheritance :
Program :
<?php

// define a parent class
class Animal {
  public $name;
  public $color;

  function __construct($name, $color) {
    $this->name = $name;
    $this->color = $color;
  }

  function eat() {
    echo "The " . $this->color . " " . $this->name . " is eating.<br>";
  }

  function sleep() {
    echo "The " . $this->color . " " . $this->name . " is sleeping.<br>";
  }
}

// define a child class that inherits from the parent class
class Dog extends Animal {
  function bark() {
    echo "The " . $this->color . " " . $this->name . " is barking.<br>";
  }
}

// create an instance of the parent class
$animal = new Animal("animal", "gray");
$animal->eat();
$animal->sleep();

// create an instance of the child class
$dog = new Dog("dog", "brown");
$dog->eat();
$dog->sleep();
$dog->bark();

?>
In this example, we define a parent class `Animal` that has two attributes `name` and `color`, and two methods `eat()` and `sleep()`. We then define a child class `Dog` that extends the parent class, and adds a new method `bark()`.

We create an instance of the parent class and call its methods, and then create an instance of the child class and call all three methods, including the new `bark()` method. The output of this program is :
Output :
The gray animal is eating.
The gray animal is sleeping.
The brown dog is eating.
The brown dog is sleeping.
The brown dog is barking.