It's not mentioned at all in the release announcement, and is but a single line in the migration guide, but...
- Static variable initializers can now contain arbitrary expressions.
In prior versions, you could not set a static variable to anything other than a manifestly constant expression. You could write static $size = 4+3;
but you couldn't refer to other variables (even previous static ones) or break the calculation out into another function for reuse. Instead, you had to initialise the static variable with some bogus value (probably null), and then every time you enter the function, explicitly check to see if it has been initialised yet or not:
8.2:
static $statvar = null;
$statvar ??= initialise_statvar();
And in earlier versions that lacked ??=
it got even uglier.
static $statvar = null;
$statvar = ($statvar === null) ? initialise_statvar() : $statvar;
It got even uglier still if you wanted to allow $statvar
to be null in your function and had to use something else to indicate that it hadn't been initialised yet. And of course the check would be made every single time the function was called.
8.3:
static $statvar = initialise_statvar();
As for "arbitrary", it can refer to volatile functions and use function arguments. Once the static variable is initialised, the initialiser isn't run again.
function foo()
{
return 42;
}
function bar($x)
{
static $thing = foo() . " now at " . microtime() . " $x";
return $thing;
}
echo bar(17), "\n";
sleep(3);
echo bar(19), "\n";
Note that both return values are the same even though $x
is different and it's three seconds later.