You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Static properties in traits don't override static properties from parent class #10935
<?phpclass A
{
protectedstatic$instance = null;
publicstaticfunctiongetInstance(...$args)
{
if(!isset(self::$instance)){
self::$instance = newstatic(...$args);
}
returnself::$instance;
}
publicfunctiongetB()
{
return B::class::getInstance();
}
}
class B extends A
{
protectedstatic$instance = null;
publicstaticfunctiongetInstance(...$args)
{
if(!isset(self::$instance)){
self::$instance = newstatic(...$args);
}
returnself::$instance;
}
}
var_dump(A::getInstance()->getB()); // B
Resulted in this output:
<?php
trait Singleton
{
protected static $instance = null;
public static function getInstance(...$args)
{
if(!isset(self::$instance)){
self::$instance = new static(...$args);
}
return self::$instance;
}
}
class A
{
use Singleton;
public function getB()
{
return B::class::getInstance();
}
}
class B extends A
{
use Singleton;
}
var_dump(A::getInstance()->getB()); // A
class A {
static$test;
}
class B extends A {
static$test;
}
A::$test = 'A';
B::$test = 'B';
var_dump(A::$test, B::$test);
// string(1) "A"// string(1) "B"
trait Foo {
static$test;
}
class A {
use Foo;
}
class B extends A {
use Foo;
}
A::$test = 'A';
B::$test = 'B';
var_dump(A::$test, B::$test);
// string(1) "B"// string(1) "B"
The RFC is super old, there's no mention on how this is supposed to behave. The docs aren't telling either. It's reasonable to expect the same behavior as the case without traits.
Activity
iluuu1994 commentedon Mar 25, 2023
Simplified example:
https://3v4l.org/Dll1m
https://3v4l.org/SClLn
The RFC is super old, there's no mention on how this is supposed to behave. The docs aren't telling either. It's reasonable to expect the same behavior as the case without traits.
[-]trait代码复用机制问题[/-][+]Static properties in traits don't override static properties from parent class[/+]Add separate static property through trait if parent already declares it