We have a couple of new features coming in to PHP 5.6 with names that sound much less exciting than the features they actually represent: "variadic functions" sound positively academic, and "argument unpacking" isn't exactly catchy. However they both use a new operator in PHP which looks like an elipsis (three dots ...) and is referred to as either the splat operator or the scatter operator. I included them in a recent version of my "Upgrading PHP" talk so I thought I'd share the examples here too in case anyone is interested.
Variadic Functions
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:
function concatenate($transform, ...$strings) {
$string = '';
foreach($strings as $piece) {
$string .= $piece;
}
return($transform($string));
}
echo concatenate("strtoupper", "I'd ", "like ",
4 + 2, " apples");
The parameters list in the function declaration has the ...
operator in it, and it basically means " ... and everything else should go into $strings
". You can pass 2 or more arguments into this function and the second and subsequent ones will be added to the $strings
array, ready to be used.
Argument Unpacking
This has a less sexy name than variadic functions, and it uses the same operator, but this is the one that made me describe PHP code as "wild" - not something that happens often! I like it because it gives a different way of using functions that already exist so it becomes relevant as soon as you upgrade to 5.6.
Variadic functions allow you to declare an array of incoming parameters, and argument unpacking allows you to pass an array in to a function expecting separate parameters in the traditional way; they are absolutely complementary to one another. To use this feature, just warn PHP that it needs to unpack the array into variables using the ...
operator. A simple example could look like this:
$email[] = "Hi there";
$email[] = "Thanks for registering, hope you like it";
mail("someone@example.com", ...$email);
You can pass all of your arguments in as an array (pro tip: associative arrays won't work here), or just the last however many you like, and PHP will take your array and pass each element in as the next parameter in turn. I think this is pretty neat :)
PHP 5.6 Is Coming
PHP 5.6 isn't released yet, it'll be out probably sometime this summer. While it's feature list isn't huge, that means the upgrade pain shouldn't be huge either - and neat additions like the two features I've picked out here are very welcome additions in my book. PHP gets better with every release and I tip my hat to all those involved - thank you all!
Lorna is an independent web development consultant, author and trainer, available for work (interesting projects only). This post was originally published at LornaJane
more
{ 0 comments... » PHP 5.6 and the Splat Operator read them below or add one }
Post a Comment