Login Register






Thread Rating:
  • 0 Vote(s) - 0 Average


Tutorial PHP Object Inheritance filter_list
Author
Message
PHP Object Inheritance #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]

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.)

Reply

RE: PHP Object Inheritance #2
Simple, yet well detailed guide.

I don't come across too many tutorials referencing classes.
Good work.
[Image: AD83g1A.png]

Reply

RE: PHP Object Inheritance #3
great work on your tutorial. Smile
My IT skills that I know perfect is SQL, HTML ,css ,wordpress, PHP.
coding skills that I know is Java, JavaScript and C#

Reply

RE: PHP Object Inheritance #4
good work thanks mate !!
Telegram : @xF0rGeT

Reply

RE: PHP Object Inheritance #5
great work on your tutorial.

Reply







Users browsing this thread: 1 Guest(s)