...$str
is called a splat operator in PHP (other languages, including Ruby.)
This feature allows you to capture a variable number of arguments to a function, combined with "normal" arguments passed in if you like. It's easiest to see with an example:
<?php
function concatenate($transform, ...$strings) {
$string = '';
foreach($strings as $piece) {
$string .= $piece;
}
return($transform($string));
}
echo concatenate("strtoupper", "I'm ", 20 + 2, " years", " old.");
Output
I'M 22 YEARS OLD.
Latest feature
After PHP 5.5.x, arrays and traversable objects can be unpacked into argument lists when calling functions by using the ...
operator.
<?php
function add($a, $b, $c) {
return $a + $b + $c;
}
$operators = [2, 3];
echo add(1, ...$operators);
?>
Output
6
That's cool. 😎
Top comments (0)