Method Signature Validation for Abstract Trait Methods in PHP 8.0

Traits can have abstract methods. Any class that uses a trait with an abstract method must implement that method. In versions prior to PHP 8.0, the signature of abstract trait method is not validated against the implementing class method.

Let’s say we have a CommandTrait trait with an abstract method.

CommandTrait.php
<?php

trait CommandTrait
{
    abstract public function run(array $args): int;
}

We create a ReadFileCommand class that uses a trait and implements its abstract method. Note that signatures of these methods mismatch. Class method has different parameter type (string) and return type (bool).

ReadFileCommand.php

<?php

class ReadFileCommand
{
    use CommandTrait;

    public function run(string $args): bool
    {
        // ...
        return true;
    }
}

In versions prior to PHP 8.0, the following code doesn’t cause any errors:

main.php

<?php

require_once 'CommandTrait.php';
require_once 'ReadFileCommand.php';

$command = new ReadFileCommand();

Since PHP 8.0, the signature of abstract trait method is validated against the implementing class method. If we run the previous code snippet in PHP 8.0 or newer versions, we will get an fatal error.

Fatal error: Declaration of ReadFileCommand::run(string $args): bool must be compatible with CommandTrait::run(array $args): int in ReadFileCommand.php on line 9

A ReadFileCommand class can be rewritten as follows:

ReadFileCommand.php

<?php

class ReadFileCommand
{
    use CommandTrait;

    public function run(array $args): int
    {
        // ...
        return 1;
    }
}

Leave a Comment

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