Skip to content

static $var = xxx should support any expression #8959

Closed
@mvorisek

Description

@mvorisek

Description

https://3v4l.org/gTufh

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)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions