Preventing Inheritance and Overriding with final: PHP OOP

Advertisement:

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
2
3
4
5
6
7
8
9
10
11
< ?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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
< ?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

Preventing Inheritance and Overriding with final: PHP OOP


You need to a flashplayer enabled browser to view this YouTube video

YouTube Link: http://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.

Advertisements

Leave a Reply

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