Skip to content

Static properties in traits don't override static properties from parent class #10935

Closed

Description

@vscing

Description

The following code:

<?php

class A
{
    protected static $instance = null;

    public static function getInstance(...$args)
    {
        if(!isset(self::$instance)){
            self::$instance = new static(...$args);
        }
        return self::$instance;
    }

    public function getB()
    {
        return B::class::getInstance();
    }
}

class B extends A
{
    protected static $instance = null;

    public static function getInstance(...$args)
    {
        if(!isset(self::$instance)){
            self::$instance = new static(...$args);
        }
        return self::$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

But I expected this output instead:

var_dump(A::getInstance()->getB()); // B

PHP Version

PHP 8.2.3

Operating System

mac 13.0.1

Activity

  1. iluuu1994 commented on Mar 25, 2023

    @iluuu1994
    Member

    Simplified example:

    https://3v4l.org/Dll1m

    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"

    https://3v4l.org/SClLn

    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.

  2. self-assigned this
    on Mar 25, 2023
  3. changed the title [-]trait代码复用机制问题[/-] [+]Static properties in traits don't override static properties from parent class[/+] on Mar 25, 2023
  4. added a commit that references this issue on Jul 19, 2024
    9a250cc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions