Private Method Declared as Final Emits Warning in PHP 8.0

The final keyword can be applied on class methods. When parent class has method that declared as final then child classes cannot override this method.

Private methods cannot be accessed outside the class. To declare a private method as final doesn’t make sense because private methods cannot be overridden by child classes. Since PHP 8.0, the private method declared as final emits a warning.

Let’s say we have a Cat class that has makeSound private method declared as final.

Cat.php

<?php

class Cat
{
    final private function makeSound(): void
    {
        echo 'Meow';
    }
}

Example will output:

Warning: Private methods cannot be final as they are never overridden by other classes in Cat.php on line 5

Note that private constructor declared as final does not emit a warning.

Dog.php

<?php

class Dog
{
    final private function __construct() {} // No warning
}

Leave a Comment

Your email address will not be published. Required fields are marked *