Use Override Attribute in PHP 8.3

Use Override Attribute in PHP 8.3

Since PHP 8.3, we can use #[Override] attribute. Applying the #[Override] attribute to a method, PHP will guarantee that a method with a matching name is present in either a parent class or an implemented interface.

Let's say we have two classes. SiberianHusky class extends Dog class and overrides the makeSound method. This method is marked with the #[Override] attribute in the SiberianHusky class.

Dog.php

<?php

class Dog
{
    public function makeSound(): void
    {
        echo 'Woof';
    }
}

SiberianHusky.php

<?php

class SiberianHusky extends Dog
{
    #[Override]
    public function makeSound(): void
    {
        echo 'Woof!!!';
    }
}

Now, let's consider a scenario where, at some point, the method name of the parent class changes to emitSound:

Dog.php

<?php

class Dog
{
    public function emitSound(): void
    {
        echo 'Woof';
    }
}

Before the implementation of the #[Override] attribute, there was no way to know that the makeSound method in the SiberianHusky class no longer overrides the renamed method. This lack of clarity could potentially result in unexpected bugs.

Adding the #[Override] attribute to a method clearly indicates of overriding a parent method, simplifying the refactoring process. This is because the elimination of an overridden parent method will be identified, triggering an error.

Fatal error: SiberianHusky::makeSound() has #[\Override] attribute, but no matching parent method exists ...

Leave a Comment

Cancel reply

Your email address will not be published.