Site icon Leonid Mamchenkov

Creating Strictly Typed Arrays and Collections in PHP

This SitePoint PHP blog post (read at Planet PHP if the site is unavailable) brings to light a very useful feature available since PHP 5.6 – ellipses in functional arguments, which allows to define a variable number of arguments to a function.

I’ve seen the mentions of ellipses a few times now, but I assumed that it was a PHP 7 feature.  Turns out PHP 5.6 users can enjoy it as well:

<?php
function sum(...$numbers) {
    $acc = 0;
    foreach ($numbers as $n) {
        $acc += $n; 
    }   
    return $acc;
}
echo sum(1, 2, 3, 4); // prints out 10

This is very useful, but, as SitePoint PHP blog most mentions, it can be made even more useful with type hinting of the arguments.  For example:

<?php 
class Movie { private $dates = [];
    public function setAirDates(\DateTimeImmutable ...$dates) { 
        $this->dates = $dates;
    }   

    public function getAirDates() {
        return $this->dates;
    }   
}

The limitation is that you can only hint a single type for all the arguments. The workaround this is to use collection classes, which basically work as strictly typed arrays.

Exit mobile version