What is the meaning of final class and final method in PHP?

The final keyword is used to stop inheritance. If a class is marked final, no other class can extend it. If a method is marked final, child classes can not override it.

<?php
class Base {
    final public function show() {
        echo "This method can not be changed";
    }
}

class Child extends Base {
    // Writing show() here would give a fatal error
}

$c = new Child();
$c->show();
?>

Output:

Tutorials Class - Output Window

This method can not be changed

A final class is written like this:

<?php
final class Util {
    public static function version() {
        return "1.0";
    }
}

// class Other extends Util {}  // Fatal error: a final class can not be extended
?>

When to use it: when a class or method must not be changed, for example a security check or a core logic. Note that properties can not be final, but from PHP 8.1 you can use readonly for properties that must not change after setting.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.