Building a Singleton Trait with PHP 5.4

后端 未结 5 2051
温柔的废话
温柔的废话 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:42

    This is guys all what you need. If you wish you could use private static member, but there is no a real need... Tested, works despite the fact that you might think that static will be global or something :)

    trait Singleton
    {
        /**
         * Singleton pattern implementation
         * @return mixed
         */
        public static function Instance()
        {
            static $instance = null;
            if (is_null($instance)) {
                $instance = new self();
            }
            return $instance;
        }
    }
    

    usage:

    class MyClass
    {
     use Singleton;
    }
    

提交回复
热议问题