Type safety in PHP arrays

PHP allows for gradual typing since version 7.0. However, it’s 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 only allows integers as arguments.

Variadic functions can handle an infinite number of arguments which 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 it is possible to unpack arrays or traversable objects into a list of arguments again by using the splat operator (...).

A big downside might be that variadics have to be the last argument in a function and thus are 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 to 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 an RFC which has been open for a few years now but still is under development - and I don’t think that it will be released soon.

Tags: ,

Categories:

Updated: