Single Inheritance: PHP OOP

Inheritance is a way to reuse the code of existing objects.
In this video tutorial we’re illustrating single inheritance mechanism.

In this tutorial, we take a class called Vehicle with 3 attributes – color, accelerate and decelerate. And 3 methods – design, acceleration, deceleration.

Vehicle Class

< ?php
  class Vehicle
  {
   public $color;
   public $accelerate;
   public $decelerate;
   
   function design($assign)
   {
    $this->color = $assign;
   }
   function acceleration($positive)
   {
    $this->accelerate = $positive;
   }
   function deceleration($negetive)
   {
    $this->decelerate = $negetive;
   }
  }
?>

Using the methods – design, acceleration and deceleration we assign values to the public attributes color, accelerate and decelerate.

Inherit Vehicle Class To Class Car
inheritance.php

< ?php
  class Vehicle
  {
   public $color;
   public $accelerate;
   public $decelerate;
   
   function design($assign)
   {
    $this->color = $assign;
   }
   function acceleration($positive)
   {
    $this->accelerate = $positive;
   }
   function deceleration($negetive)
   {
    $this->decelerate = $negetive;
   }
  }
  
  class Car extends Vehicle
  {
   
  } 
?>

Now create objects benze and bmw of class Car.

Objects of Class Car
vehicles.php

< ?php
  include_once("inheritance.php");
  
  $benze = new Car();
  $benze->design("Red");
  echo $benze->color;
  
  $bmw  = new Car();
  $bmw->design("Silver");
  echo "
".$bmw->color; $benze->acceleration(20); echo "
".$benze->accelerate; $benze->deceleration(5); echo "
".$benze->decelerate; ?>

Here, using the methods – design, acceleration and deceleration we assign attribute values to individual cars.

Single Inheritance: PHP OOP



YouTube Link: https://www.youtube.com/watch?v=pdDqtHlkzEY [Watch the Video In Full Screen.]



Uses of Inheritance:
Re-use of code.
Less and cleaner looking code.
Ease of understanding of code.
Ease of maintenance of project.

View Comments