PHP 5.6

Earlier I wrote about PHP 5.5 that brought us generators and the finally keyword. PHP 5.6 also brings us some nice improvements in the language. PHP is improving with every release, the only problem is that we cannot use these nice features in production because distributions are still a few releases behind.

Constant scalar expressions

In PHP before 5.6 a constant can only be a real constant and not a calculated constant. There are a lot of use cases where this could be really handy and with PHP 5.6 this is added to the language.

class User { 
   const TYPE_1 = 1;
   const TYPE_2 = TYPE_1 + 1;
}

Variadic functions

A well known problem in PHP was giving multiple unknown parameters with a function. The function func_get_args() could be used to achieve that but it was not a very elegant solution.

function foo() {
   $args = func_get_args();
}

From PHP 5.6 this can be replaced by the following

function bar(...$args) {
   print_r($args);
}
bar(1,23);

When executed this will produce the following result:

Array
(
    [0] => 1
    [1] => 23
) 

This is the same as with func_get_args() but a bit more elegant and easier to understand. Also the function declaration is more clear what it accepts instead of the hidden functionality of the func_get_args() function call. Now it would be interesting to rewrite functions that uses this function to new variadic function style.

Argument unpacking

The other way around an array can be given as a argument to a function and can be unpacked automatically. This makes the function definition very concise. The … will unpack the variable, in other languages this is called the splat operator.

function foo($a, $b, $c) {
   print $c;
}

$args = [1,2,3];

foo(...$args);

The result of above snippet is 3. The array will be unpacked and assigned to the three variables.

More reading

  • http: