Inheritance in php

In inheritance , when a class drives from another class.

Child class inherit parent class using extends keyword in child class, means that child class will inherit all methods and properties from parent class and child class also have own methods and properties.

class Parent {
  public $name;
  public $color;
  public function __construct($name, $color) {
    $this->name = $name;
    $this->color = $color;
  }
  public function intro() {
    echo "The Parent is {$this->name} and the color is {$this->color}.";
  }
}

// Child is inherited from Parent
class Child extends Parent {
  public function message() {
    echo "Am I a Parent or a child? ";
  }
}
$Child = new Child("Child", "red");
$Child->message();
$Child->intro();

Output

 Am I a Parent or a child? The Parent is Child and the color is red. 

Leave a Reply

Your email address will not be published. Required fields are marked *