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.
<PreviousNext>
^ Back to Top