Building a Singleton Trait with PHP 5.4

后端 未结 5 2033
温柔的废话
温柔的废话 2020-12-14 02:22

We recently had a discussion if it was possible to build a trait Singleton PHP Traits and we played around with it a possible Implementation but ran into issues

5条回答
  •  轮回少年
    2020-12-14 02:49

    I created one a while ago when i was bored trying to learn traits. It uses reflection and the __CLASS__ constant

    Trait:

    trait Singleton
    {
    private static $instance;
    
    public static function getInstance()
    {
        if (!isset(self::$instance)) {
            $reflection     = new \ReflectionClass(__CLASS__);
            self::$instance = $reflection->newInstanceArgs(func_get_args());
        }
    
        return self::$instance;
    }
    final private function __clone(){}
    final private function __wakeup(){}
    }
    

    This way you can continue to use the __construct() method and don't need to use an arbitrary function as the constructor.

提交回复
热议问题