php
  1. php-final-keyword

Php Final Keyword

The final keyword in PHP is used to restrict the inheritance of a class or the overriding of a method. If a class is declared as final, it cannot be extended by any other class. Also, if a method is declared as final, it cannot be overridden by any of its child classes.

Syntax

final class ClassName {
   //class code here
}
class ParentClass {
   final function someFunction() {
      //code here
   }
}

Example

final class Car {
   public function showDetails(){
      return "This is a car.";
   }
}

class SportsCar extends Car {
   //code here
}

Output:

Fatal error: Class SportsCar may not inherit from final class (Car)

Explanation

When we declare a class or function as final, it means that anyone who tries to extend that class or override that function will get a fatal error. This ensures that the final class or function is not modified in any way, thus maintaining the integrity of the application.

Use

  • To prevent any child class from modifying the behavior of the final class
  • To prevent any child class from overwriting the final method of the parent class

Important Points

  • The final keyword can only be used for classes and class methods.
  • The final class cannot be extended by any other class.
  • The final method cannot be overridden by any of its child classes.

Summary

  • The final keyword in PHP is used to restrict the inheritance of a class or the overriding of a method.
  • When we declare a class or function as final, it means that anyone who tries to extend that class or override that function will get a fatal error.
  • The final keyword can only be used for classes and class methods.
  • The final class cannot be extended by any other class.
  • The final method cannot be overridden by any of its child classes.
Published on: