Final Keyword in PHP | Object Oriented Concepts

A class can inherit properties from a parent class. However, it can only inherit public and protected properties. Also, the child class can override methods of the parent class. PHP introduces the Final Keyword, which prevents the child class from overriding methods of the parent class by prefixing it with Final Keyword. Additionally, no other class can inherit a Final Class. In this article, we will discuss the Final Keyword in PHP.

You might want to go through Function Overriding in PHP before reading this article.

What is the Final Keyword in PHP?

Prefixing a method in the parent class with Final Keyword in PHP prevents any child class from overriding it. Also, a Class cannot inherit a Class which is Final.

Note: Properties cannot be declared final, only classes and methods may be declared as final.

Final Methods

If you don’t want another class to override a particular method in a class, then you can declare it final. You can do this by prefixing the Final Keyword in the function definition.

<?php
	class BaseClass {
                //Here this method is declared final by prefixing the Final Keyword                   
		public final function finalMethod() {
                       //some logic
		}
	}
?>

For instance, let’s see what happens when you try to override the above final method.

<?php        
        class ChildClass extends BaseClass {
		public function finalMethod() {

		}
	}
?>

It results in the following error:

Cannot override final method BaseClass::finalMethod()

Final Class

Similarly, you can declare a Class Final by prefixing the final keyword in PHP before the Class Definition. No other Class will be able to inherit a Final Class. A Final Class may or may not contain Final methods. However, it is useless to declare Final Methods in a Final Class because inheritance is not possible.

<?php
        //BaseClass is declared final by prefixing Final Keyword
	final class BaseClass {
		public function finalMethod() {

		}
	}

	class ChildClass extends BaseClass {
		public function finalMethod() {

		}
	}
?>

Extending a Final Class results in the following error:

Class ChildClass may not inherit from final class (BaseClass)

Conclusion

In conclusion, we discussed the Final Keyword in PHP. It comes handy when you don’t want a method or a class to override your method. It should be decided very carefully which Methods/Classes should be final while deciding the architecture. You can learn more about it on the Official PHP Documentation.

Also feel free to go through other PHP articles on Concatly!

Spread the Knowledge

Leave a Reply

Your email address will not be published. Required fields are marked *