PHP OOPs - The final Keyword

The final Keyword is used for below purposes.

  • The final keyword can be used to prevent class inheritance. Final class can not be inherited by another class.
  • The final keyword can be used to prevent method overriding. Final Method of parent class can not be overriden by method of child class.

PHP Syntax:

final class class_name

final function function_name

PHP Example :

Look at below example. Child Cricket class can not extend Game class because Game class is final which prevent class inheritance.

<?php
//code by aryatechno!
 
final class Game {
   public function details() {
    // code to be executed.
  }
}

class Cricket extends Game {  
  // Generates PHP Fatal error:  Class Crircket may not inherit from final class (Game)
  public function details() {
    // code to be executed.
  }
}
?>

Output:
PHP Fatal error:  Class Cricket may not inherit from final class (Game) in c:\xampp\htdocs\page.php on line 15

PHP Example 2 :

Look at below example. Final method register of Jobs class can not be overriden by method register of Candidate class. Because final keyword prevents it from overriden.

<?php
//code by aryatechno!
 
 class Jobs{
  final public function register() {
    // code to be executed.
  }
}

class Candidate extends Jobs{  
 
  public function register() {
    // Generates PHP Fatal error:  Cannot override final method Jobs::register()
    // code to be executed.
  }
}
?>

Output:

PHP Fatal error:  Cannot override final method Jobs::register() in c:\xampp\htdocs\page.php on line 12

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

67804