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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With