Final keyword in PHP

 

In Php we can use final keyword with Classes and Methods.

1. Final Classes Prevent inheritance

2. Final Methods Prevent Method Overriding

Final Classes:

If we declare a class as final class then subclass can not be extend parent class.


	final Class Parent
	{
		public function show($a,$b)
		{
			$mul=$a*$b;
			echo "Multiplication of given no=".$mul;
		}
	} 

	class Child extends Parent
	{
		function show($a,$b)
		{
			$sum=$a+$b;
			echo "Sum of given no=".$sum;
		}
	}
		
	$obj= new Child();
	$obj->show(100,100);
	
Output Fatal error: Class Child may not inherit from final class (Parent) in C:xampp\htdocs\test\index.php on line 17

Final Methods:

If we declared a method as final method in parent class then subclass can not be overriding parent class method.

class Parent	
{
	final function show($a,$b)
	{
		$mul = $a*$b;
		echo "Multiplication of given no=".$mul;
	}
} 
class Child extends Parent
{
	public function show($a,$b)
	{
		$sum = $a+$b;
		echo "Sum of given no=".$sum;
	}
}	 
$obj= new Child();
$obj->show(100,100);


Output Fatal error: Cannot override final method Parent::show() in C:xampp\htdocs\test\index.php on line 18

Leave a Reply

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

Follow by Email
LinkedIn
Share
Instagram