Final keyword in PHP


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

Updated on: 02-Jan-2020

562 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements