Jump to content
Sign in to follow this  
sunjester

[tut] PHP Object Inheritance

2 posts in this topic

Offline

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.

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.

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.

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

class Car extends Vehicle
{
        function changeColor($c)
        {
                $this->color = "new color, ".$c;
        }
}

References

  • https://www.ibm.com/developerworks/rational/library/content/RationalEdge/sep04/bell/index.html
  • https://www.draw.io/
  • http://php.net/manual/en/language.oop5.inheritance.php
  • https://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)

Share this post


Link to post
Share on other sites
Offline

I was wanting to learn this and here you are giving it and i didn't even realize

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.

About us

3rdWorld.cc is a cracking forum community that suits the purpose of everyone. We offer paid program for free, cracking tools, combolists, marketplace and many more. You can also expand on knowledge and participate in active discussions.

×