How to Access Overridden Methods in PHP



PHP




In this article, we show how to access overridden methods in PHP.

An overriden method is one that is overridden usually by a parent class.

Let's say you create a method named move() in a parent class that states, "I run".

Then you create a child class and use the same method named move() that states, "I run fast".

You have overridden the parent method in the child class.

The move() method originally stated, "I run" and in the child class now states "I run fast".

So in the child class, even though, you've overridden the move() method, there may be times when you still want to use the parent method. And you still can access the parent method.

The PHP code below shows how to access the parent method when you've overridden the method in the child class.



So in the code above, we create a class named animals.

In this function, we have a function named move() which accepts a parameter named $speed. This function outputs "I run at the number of miles per hour".

We then create a new class named cheetahs, which is a child class of the animals class.

We create the same method move() which accepts the $speed parameter. If the $speed is greater than 60, we echo, "As a cheetah, I run fast, at how many miles per hour". Else, we echo the original parent function.

To access the overridden method in PHP, we use the parent keyword, followed by 2 colons (::), followed by the function.

So to access the overridden parent method, in this case, the code to do so is, parent::move($speed).

And this is all that is required to access a parent class in PHP.

Running the code above yields the following output below.



Actual PHP Output


I run at 10 miles per hour
As a cheetah, I run fast, at 75 miles per hour
I run at 15 miles per hour


Related Resources

How to Create a Class Destructor in PHP

HTML Comment Box is loading comments...