What is the use of the final keyword

The final keyword in PHP is used to declare that a class cannot be extended or a method cannot be overridden. This is particularly useful when you want to prevent subclasses from altering the functionality of a class or method.

When applied to a class, no other class can inherit from it. When applied to a method, it cannot be overridden by any subclasses. Using final ensures that your class's behavior remains consistent and controlled.

Here is an example of how to use the final keyword in PHP:

<?php final class BaseClass { public function show() { echo "This is the BaseClass."; } } // The following class will cause a fatal error // because BaseClass is declared final. // class SubClass extends BaseClass { // } $obj = new BaseClass(); $obj->show(); // Output: This is the BaseClass. ?>

final php keyword programming inheritance