3

PHP has variadic argument unpacking since version 5.6.

function doSomething(User ...$users) {
     return count($users);
}
$userOrNoUserList = [$user1, null, $user2];
doSomething(...$userOrNoUserList); // wanted: 3

This throws the following error:

Catchable fatal error: Argument 2 passed to doSomething() must be an instance of user, null given

But I want to preserve the list structure inside doSomething(); I do not want to filter null values before invocation. Is it possible to allow null values too?

Nicolas Heimann
  • 2,561
  • 16
  • 27

1 Answers1

5

You have to define a Nullable Type using the ? character before the type User (available in PHP 7.1.0):

function doSomething(?User ...$users) {
     return count($users);
}

Then you could call:

$userOrNoUserList = [$user1, null, $user3];
doSomething(...$userOrNoUserList); // 3
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87