TOC
Classes:

The "final" keyword

In the previous chapters, we saw how we could let a class inherit from another class. We also saw how you could override a function in an inherited class, to replace the behaviour originally provided. However, in some cases you may want to prevent a class from being inherited from or a function to be overridden. This can be done with the final keyword, which simply causes PHP to throw an error if anyone tries to extend your final class or override your final function.

A final class could look like this:

final class Animal
{
    public $name;
}

A class with a final function could look like this:

class Animal
{
    final public function Greet()
    {
        return "The final word!";    
    }
}

The two can be combined if you need to, but they can also be used independently, as seen in the examples above.


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!