Type safety in PHP arrays

PHP allows gradual typing since version 7.0. However, this is not yet possible with arrays and it doesn’t provide generic types like for example C# or Java. As a simple workaround you can create collection classes to simulate this behaviour.

The first example demonstrates a typical collection class which accepts an array in the constructor. All types are allowed here, the given array is not checked for its contents.

<?php
declare(strict_types=1);
class CollectionUnsafe
{
    private $values;

    public function __construct(array $values)
    {
        $this->values = $values;
    }
}

$col = new CollectionUnsafe([123, '456', 7.8]);

The second example defines a collection class with a variadic function/constructor that allows only integers as arguments.

Variadic functions can handle a infinite number of arguments and these will be stored in the named variable as an array. It seems to be unhandy to give multiple values as arguments to a new collection instance, but luckily by using the splat operator (...) it is possible to unpack arrays or traversable objects into a list of arguments again.

A big downside might be that variadics have to be the last argument in a function, and thus it is allowed only once.

<?php
declare(strict_types=1);
class CollectionSafe
{
    private $values;

    public function __construct(int ...$values)
    {
        $this->values = $values;
    }
}

$col = new CollectionSafe(...[123, '456', 7.8]); // type error
$col = new CollectionSafe(...[123, 456, 78]); // fine
$col = new CollectionSafe(123, 456, 78); // same as above

At the first look, this seems to be a good solution. But on the other hand, you have define the same collection for each type again and again. That’s one of the reasons why PHP really needs generic type support. There is a RFC open for a few years, but it is still under development, and I don’t think that it will be released soon.

Tags: ,

Categories:

Updated: