PHP final Keyword

PHPServer Side ProgrammingProgramming

Introduction

Using final keyword in the definition of an instance method in a PHP class prevents it from being overridden by child class. Similarly, if final is used in definition of class itself, such a class cannot be extended.

Syntax

final class myclass {}
class myclass{
   final method mymethod(){}
}

final method example

In following example, attempt tooverride final method results in error

Example

 Live Demo

<?php
class parentclass{
   final function test(){
      echo "final method in parent class";
   }
}
class childclass extends parentclass{
   function test(){
      echo "overriding final method in parent class";
   }
}
$obj=new childclass();
$obj->test();
?>

Output

Output shows following error message

PHP Fatal error: Cannot override final method parentclass::test() in line 16

final class example

Similarly a final class can't be inherited from as following example shows

Example

 Live Demo

<?php
final class parentclass{
   final function test(){
      echo "final method in parent class";
   }
}
class childclass extends parentclass{
   function test(){
      echo "overriding final method in parent class";
   }
}
$obj=new childclass();
$obj->test();
?>

Output

Output shows following error message

PHP Fatal error: Class childclass may not inherit from final class (parentclass) in line 16
raja
Published on 18-Sep-2020 11:08:57
Advertisements