Home >>PHP Object Oriented >PHP Final Class

PHP Final Class

Use of final class in PHP

The final keyword prevents child classes from overriding a method by prefixing the definition with final. It means if we define a method with final then it prevents us to override the method.

<?php
class A	
{
final function show($x,$y)
{
$sum=$x+$y;
echo "Sum of given no=".$sum;
}
} 
class B extends A
{
 function show($x,$y)
{
$mult=$x*$y;
echo "Multiplication of given no=".$mult;
 }
}	 
$obj= new B();
$obj->show(100,100);
?>
Output Fatal error: Cannot override final method A::show() in C:xampplitehtdocs1aa.php on line 18

In the above example The class A which is my parent class. In which show method is marked by the final. It means that the show method can not override in any its child class.

To see the error class B define which is extended by A. It means B is the child class of A. In B it is trying to define the final method (show) in class B. Which will produce the fatal error with message Cannot override final method A:: show(). It means we can not define the final method of parent class in its child class.

Final use before the class

If the class itself is being defined final then it can not be extended. It means when we define a class with final then it will not allow defining its child class.

<?php
final Class A

{

function show($x,$y)

{

$sum=$x+$y;

echo "Sum of given no=".$sum;

 }

} 

class B extends A

{

function show($x,$y)

{

$mult=$x*$y;

echo "Multiplication of given no=".$mult;

 }

} 
	
$obj= new B();

$obj->show(100,100);

?>
Output Fatal error: Class B may not inherit from final class (A) in C:xampplitehtdocs1aa.php on line 17

In the above example class A defines with the final. It means this class can not be extended. When class B defined with extend A ( which means B is the child class of A). But It produces the error with the message "Class B may not inherit from final class (A)". It means that it will not allow creating any child class of A. It means that the final class can not be inherited.


No Sidebar ads