Final keyword in PHP

PHPServer Side ProgrammingProgramming

The final keyword is used in PHP for methods and classes. The final for methods prevent method overriding, whereas for classes with final prevent Inheritance.

Example

To work with the final keyword in PHP, the code is as follows. Here, we have the final method−

 Live Demo

<?php
   class Base {
      final function display() {
         echo "Base class function declared final!";
      }
      function demo() {
         echo "Base class function!";
      }
   }
   class Derived extends Base {
      function demo() {
         echo "Derived class function!";
      }
   }
   $ob = new Derived;
   $ob->demo();
?>

Output

This will produce the following output−

Derived class function!

Example

Let us now see an example wherein we have a final class −

 Live Demo

<?php
   final class Base {
      final function display() {
         echo "Base class function declared final!";
      }
      function demo() {
         echo "Base class function!";
      }
   }
   class Derived extends Base {
      function demo() {
         echo "Derived class function!";
      }
   }
   $ob = new Derived;
   $ob->demo();
?>

Output

This will produce the following output i.e. an error since we tried creating a derived class from a final base class−

PHP Fatal error: Class Derived may not inherit from final class (Base) in /home/cg/root/6985034/main.php on line 19
raja
Published on 27-Dec-2019 06:08:31
Advertisements