SPONSORS

PHP Tutorials and Videos
9093 views · 5 years ago
Type Arrays with Variadic Functions in PHP

It's a very common task to work with an array of values, each of the same type. Integers, strings, all kinds of objects etc. But PHP is still a weakly typed language, so it's hard to tell if an arbitrary array actually contains only values of a given type.
Of course, you can always use a class:
class IntArray {
private $values = [];
public function add(int $value) {
$this->values[] = $value;
}
}

Then, whenever you need an array of integers, you may write something like this:
class BatchProcessor
{
private $ids;
public function __construct(IntArray $ids) {
$this->ids = $ids;
}
}

Not bad. You'll need a class per type, though, and that may seem a bit of an overkill for such a simple task. Luckily, same result can be achieved differently, but with the same level of confidence in every value type:
class BatchProcessor
{
private $ids;
public function __construct(int ...$ids) {
$this->ids = $ids; }
}

Voila - no need for extra class! This approach uses the PHP 7's type hinting for scalar types, in conjunction with Variable length argument lists available since PHP 5.6. In fact, variable-length argument lists have been around since probably the very first version of the language, but in 5.6 they were revisited and got some nice syntactic sugar in form of "...", so you declare and call them as easy as this:
function func(...$args){...}
$args = [1, 2, 3];
func(...$args);

The approach can work with any type-hinting available in PHP, and I hope you find it somewhat useful! Comment, discuss share and ask questions - I'll be around.

SPONSORS