Skip to content

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

Closed
@vscing

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

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions