Preventing Inheritance and Overriding with final: PHP OOP

Video tutorial illustrating, how to prevent inheritance and overring using final keyword, in Object Oriented PHP.

In this program, we take two classes A and B, and then extend Class A to Class B.
Now using the final keyword, we’ll show how to avoid extending class A to class B or any other classes. Next, we’ll also show, how to use final keyword to prevent method overriding.

Avoiding Inheritance

<?php
 final class A
 {
 
 }
 
 class B extends A
 {
 
 }
?>

This through’s following fatal error:

Fatal error: Class B may not inherit from final class (A) in C:\wamp\www\OOP\final.php on line 16

So, using the keyword final infront of the class name prevents it from inheritance.

Avoiding Overriding of method

<?php
class A
{
final function display()
{
echo "Inside class A";
}
}
 
class B extends A
{
function display()
{
echo "Inside class B";
}
}
?>

This through’s following fatal error:

Fatal error: Cannot override final method A::display() in C:\wamp\www\OOP\final.php on line 16

So, using the keyword final infront of the method name prevents it from being overriden.

Related:
If you want to know the basics of Inheritance and Overriding, go through this short notes before proceeding
Single Inheritance: PHP OOP
Overriding: PHP OOP

Video Tutorial: Preventing Inheritance and Overriding with final: PHP OOP



YouTube Link: https://www.youtube.com/watch?v=NXsD908RSVE [Watch the Video In Full Screen.]


Sometimes preventing inheritance and avoiding overriding of certain methods becomes necessary inorder to maintain the sanity or data integrity while coding.