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.

php-oop-single-inheritance

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

Vehicle Class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
< ?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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
< ?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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
< ?php
include_once("inheritance.php");
 
$benze = new Car();
$benze->design("Red");
echo $benze->color;
 
$bmw  = new Car();
$bmw->design("Silver");
echo "<br />".$bmw->color;
 
$benze->acceleration(20);
echo "<br />".$benze->accelerate;
 
$benze->deceleration(5);
echo "<br />".$benze->decelerate;
?>

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

Single Inheritance: PHP OOP


[youtube https://www.youtube.com/watch?v=pdDqtHlkzEY]

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.