Explain final class and final method in PHP.

PHPObject Oriented ProgrammingProgramming

The final keyword is introduced by PHP5 related to the object-oriented programming concept.

But before we move on to the final, we need to ensure that we have a good understanding of the inheritance concept. In inheritance, we can inherit a class from another class. Also, we can override a function in an inherited class, to replace the behavior originally provided. In some cases, we might need to keep a class from being inherited from or we may need to prevent a function to be overridden. This can be achieved with the final, by prefixing the class and function with the final keyword.which essentially causes PHP to produced an error in the event that anybody attempts to extend a final class or override final function.

Note:

we can only use the final keyword with methods and classes.

Let's demonstrate the concept with the help of the below examples.

Example:

We can't override the parent class function.

<?php
   class BaseClass{
      final function calculate($val1,$val2){
         $sum = $val1+$val2;
         echo "Sum of given no=".$sum;
         }
      }
   class ChildClass extends BaseClass{
      function calculate($x,$y){
         $mult=$val1*$val2;
         echo "Multiplication of given no=".$mult;
         }
      }
   $obj= new ChildClass();
   $obj->show(10,10);
?>

Output:

PHP Fatal error: Cannot override final method BaseClass::calculate()

Explanation:

In the above example the class BaseClass which is parent class. In which the calculate method is marked as final. It implies that we cannot override the show method in any of its child classes. To identify the error  ChildClass is trying to define the final method show (). This will produce a fatal error, It implies that the final method of parent class can't be defined in its child class.

Example:

Utilize of "Final" keyword Before The Class

<?php
   final Class BaseClass{
      function printData($val1,$val2){
         $add=$val1+$val2;
         echo "Sum of given no=".$s;
         }
      }
   class Child extends BaseClass{
      function printData($val1,$val2){
         $m=$val1*$val2;
         echo "Multiplication of given no=".$m;
         }
      }
   $obj= new Child();
   $obj->printData(20,20);
?>

Output:

PHP Fatal error: Class Child may not inherit from final class (BaseClass)

Explanation:

In the above example class BaseClass define with the final, that result we can not extend this class. When class Child tries to extend from BaseClass ( which implies Child is the child class of BaseClass). For this situation, PHP throws an error message “Class Child may not inherit from the final class (BaseClass)”.It implies that it won't permit creating any child class of BaseClass.

raja
Published on 07-Jun-2019 11:51:44
Advertisements