How to Create a Final Method in PHP 


               


How to Create a Final Method in PHP

php


In this article, we show how to create a final method in PHP.

A final method that cannot be overridden.

So if you create a final method in a parent class, you cannot override that method in a child class.

If you attempt to define a method in a child class that is the same as a final method in a parent class, a fatal error will be thrown.

Once a method is declared to be final, another inherited class cannot use the same method name. The method in the parent class cannot be modified. In other words, it's final, as the name implies.

To create a final method in PHP, you simply have to put the keyword final before the keyword function.

So the following code below creates a final method named move().



So the class above creates a class named animals.

Being that we've declared this function to be final, it cannot be modified in any child class at all. No child class can even use the same method in name, or a fatal error will be output.

Just to show you the output you would get if you created a child class and attempted to use the same method name move(), I created a child class and named a method in the child class the same name, move(). In return, the program output a fatal error, such as shown below.

Fatal error: Cannot override final method animals::move()

A final method is one where you absolutely do not want any change to the method at all in the parent class or any child classes.

In this way, a final class can be seen as an immutable method.

And making a method final, as you can see, is really simple. The final keyword simply needs to precede it.

Related Resources

How to Create a Final Class in PHP




HTML Comment Box is loading comments...