PHP Object Inheritance 12-28-2018, 11:33 PM
#1
Introduction
In this article we will be creating objects and demonstrating inheritance. If you do not know how to create a class in PHP then this tutorial may not be for you. The base class is sometimes called the super class. In PHP the extend keyword is used to inherit from another class. You can also inherit from a class that is being inherited from another class.
UML
Showing object inheritance in UML is pretty simple, its a line from the base class to the child class, the arrow is an outline and not solid, as pictured below. The Car class is inheriting the base class, Vehicle.
![[Image: 85sqEhx.png]](https://i.imgur.com/85sqEhx.png)
Classes
Our classes will be based on vehicles. The base class will be Vehicle. We can create other classes and inherit the methods/functions of the base class. The above UML is converted into PHP (below) to show how the inheritance works.
The Car class above will automatically have a color variable/attribute. You can use the changeColor method from the base class to set the color of the Car class.
Overloading
You can add your own method in the child class to overload the original method in the base class.
References
In this article we will be creating objects and demonstrating inheritance. If you do not know how to create a class in PHP then this tutorial may not be for you. The base class is sometimes called the super class. In PHP the extend keyword is used to inherit from another class. You can also inherit from a class that is being inherited from another class.
UML
Showing object inheritance in UML is pretty simple, its a line from the base class to the child class, the arrow is an outline and not solid, as pictured below. The Car class is inheriting the base class, Vehicle.
![[Image: 85sqEhx.png]](https://i.imgur.com/85sqEhx.png)
Classes
Our classes will be based on vehicles. The base class will be Vehicle. We can create other classes and inherit the methods/functions of the base class. The above UML is converted into PHP (below) to show how the inheritance works.
Code:
class Vehicle
{
public $color;
function changeColor($c)
{
$this->color = $c;
}
}
class Car extends Vehicle
{
}
The Car class above will automatically have a color variable/attribute. You can use the changeColor method from the base class to set the color of the Car class.
Code:
$car = new Car();
$car->changeColor("red");
Overloading
You can add your own method in the child class to overload the original method in the base class.
Code:
class Car extends Vehicle
{
function changeColor($c)
{
$this->color = "new color, ".$c;
}
}
References
(This post was last modified: 12-28-2018, 11:33 PM by sunjester.)