Closed
Description
Description
https://3v4l.org/G1EiN - this works, static $var
can hold an object, only the initial value declaration needs longer code
<?php
class Cl {
public function scalar(): void
{
static $counter = 0;
$counter++;
var_dump($counter);
}
public function obj(): void
{
static $counter = new class() {
public int $n = 0;
};
$counter->n++;
var_dump($counter->n);
}
}
$o = new Cl();
$o->scalar();
$o->scalar();
$o->obj();
$o->obj();
$o = new class() extends Cl {};
$o->scalar();
$o->obj();
Currently php emits fatal error for static $var = new class() {};
.
But static $var = ...;
should support any expression like if the assign op would not be prefixed with static
as such prefix only defines the statement should be evaluated only once per php request lifecycle & the variable kept alive.
It seems like some historical php limitation...
Instead of a fatal error, I expect this result for the test case above:
int(1)
int(2)
int(1)
int(2)
int(3)
int(3)