How to define the return type as array with its properties in PHP

Viewed 24

I have a PHP interface and its concrete class as below.

interface InterfaceA
{
    public function methodA(array $data): array;
}

class ClassA implements InterfaceA
{
    public function methodA(array $data): array
    {
        // method stuffs

        return [
            'id' => 1,
            'name' => 'Name 1'
        ];
    }
}

I need a way to strictly define the return type (array) with its properties (id, name) in the interface method.

The intention of this is when someone implements the same interface for another concrete class (say ClassB), he might have missed some properties (like 'name') from the returned array.

Is there a way in PHP (I'm using PHP 8.0), to avoid this mistake?

1 Answers

How about creating a specific class for the return type, and return not an array but an instance of this class ?! Because if think (I may be wrong) array in php are flexible and you cannot force array return type to contain a certain key.

Your class will then be :

class ReturnClassTest {
    public function __construct(public int $id, public string $name) {}
}

interface InterfaceA
{
    public function methodA(array $data): ReturnClassTest;
}

class ClassA implements InterfaceA
{
    public function methodA(array $data): ReturnClassTest
    {
        // method stuffs
        return new ReturnClassTest(1, 'Name 1');
    }
}
Related