Private Method Declared as Final Emits Warning in PHP 8.0

Private Method Declared as Final Emits Warning in PHP 8.0

The final keyword can be applied to class methods. When a parent class has a 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 the 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 a private constructor declared as final does not emit a warning.

Dog.php

<?php

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

Leave a Comment

Cancel reply

Your email address will not be published.