Skip to content

trait代码复用机制问题 #688

Closed
@vscing

Description

@vscing

From manual page: https://php.net/language.oop5.traits
trait代码复用机制问题

代码正常

<?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

代码复用不正常

<?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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions