php
  1. php-inheritance-task

PHP Inheritance Task

Syntax

class ParentClass {
  // Parent Class Properties & Methods
}

class ChildClass extends ParentClass {
  // Child Class Properties & Methods
}

Example

class Animal {
  public $name;
  public $color;

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

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

class Dog extends Animal {
  public function makeSound() {
    echo "Woof!<br>";
  }
}

$myDog = new Dog("Buddy", "Brown");
$myDog->displayInfo();
$myDog->makeSound();

Output

Name: Buddy
Color: Brown
Woof!

Explanation

Inheritance is an important concept in Object Oriented Programming. It allows for the creation of a new class based on an existing class. The new class is called the Child class, while the existing class is called the Parent class. Inheritance enables the Child class to inherit all the properties and methods of the Parent class.

In the above example, we have an Animal class that has two properties and two methods. We then created a Dog class using the extends keyword to inherit from the Animal class. The Dog class also has its own method. We then created an object of the Dog class, which inherited the two properties and two methods from the Animal class and also has its own method.

Use

Inheritance can be useful when creating new classes that are very similar to existing classes. Instead of creating a new class from scratch, inheritance allows for the new class to inherit all the properties and methods of the existing class, allowing for easier and cleaner code.

Important Points

  • To inherit from an existing class, use the extends keyword.
  • The Child class can access all the public and protected methods and properties of the Parent class.
  • The Child class can override any method of the Parent class by simply creating a new method with the same name.

Summary

Inheritance is an important concept in Object Oriented Programming that allows for the creation of a new class based on an existing class. The new class inherits all the properties and methods of the existing class, allowing for easier and cleaner code. The Child class can access all the public and protected methods and properties of the Parent class, and can override any method of the Parent class by simply creating a new method with the same name.

Published on: