Preventing Inheritance and Overriding with final: PHP OOP

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

stop-sign

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

  1. <?php  
  2.  final class A  
  3.  {  
  4.    
  5.  }  
  6.    
  7.  class B extends A  
  8.  {  
  9.    
  10.  }  
  11. ?>  

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

  1. <?php  
  2. class A  
  3. {  
  4. final function display()  
  5. {  
  6. echo "Inside class A";  
  7. }  
  8. }  
  9.    
  10. class B extends A  
  11. {  
  12. function display()  
  13. {  
  14. echo "Inside class B";  
  15. }  
  16. }  
  17. ?>  

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.