On the syntax level, these two approaches work identicaly:
<?php
function provideGenerator(): \Generator {
echo "[gInit]";
yield 0=>1;
echo "[gMid]";
yield 1=>2;
echo "[gEnd]";
}
function provideArray(): array {
return [1,2];
}
function provideIterator(): Iterator {
return new ArrayIterator(provideArray());
}
function acceptIterable(iterable $iterable) {
echo "iterable ". \gettype($iterable). ": ";
foreach ($iterable as $item) {
echo $item;
}
echo PHP_EOL;
}
function acceptVariadic(...$variadic) {
echo "variadic ". \gettype($variadic). ": ";
foreach ($variadic as $item) {
echo $item;
}
echo PHP_EOL;
}
acceptIterable(provideGenerator());
acceptIterable(provideArray());
acceptIterable(provideIterator());
acceptIterable([1,2]);
acceptVariadic(...provideGenerator());
acceptVariadic(...provideArray());
acceptVariadic(...provideIterator());
acceptVariadic(1,2);
Resulting:
iterable object: [gInit]1[gMid]2[gEnd]
iterable array: 12
iterable object: 12
iterable array: 12
[gInit][gMid][gEnd]variadic array: 12
variadic array: 12
variadic array: 12
variadic array: 12
Obviously the iterable approach has a lot of benefits:
- is not unrolling upon passing of the parameter
- allowing to pass keys
- spread operator unrolls and converts to array, not only the original type is lost, it takes O(n) time.
- spread operator has the quirk of
Error: Cannot unpack Traversable with string keys
- variadic parameter must be the last parameter, less flexible in refactoring/API extending
What are the reasons to ever use the variadic parameter?
- apart from "can be type hinted"?
My Answer:
One possible reason to use a variadic parameter instead of an iterable type-hint is if you specifically want to allow for a variable number of arguments to be passed to the function. This can be useful in cases where the number of arguments may vary and you want to be able to handle them all without having to explicitly define an iterable data structure. Additionally, variadic parameters can be more concise and easier to work with in certain situations where you don't need the additional features provided by iterable type-hinting.
Rate this post
5 of 5 based on 7652 votesComments