使用trait的功能使类变为单例。
<?php trait SingletonObject { protected static $_singleton = null; final private function __clone() {} final private function __sleep() {} final private function __wakeup() {} protected function __construct() {} /** * 返回单例 * * @return mixed */ final public static function getInstance() { if (is_null(static::$_singleton)) { static::$_singleton = static::singleton(); } return static::$_singleton; } /** * 这个方法只会被调用一次,用于生产单例的时候 * 如果类有特殊的参数,则需要重写这个方法 * * @return mixed */ protected static function singleton() { return new static(); } }
使用:
<?php class NeedSingleton { use SingletonObject; } //则直接可以使用 $s = NeedSingleton::getInstance();
如果构造类的时候需要初始化参数,则可以重写`singleton`方法:
class NeedSingleton2 { use SingletonObject; protected $config = []; protected function __construct($config) { $this->config = $config; } protected static function singleton() { $config = [ // some config ]; return new static($config); } } //或者直接重写 __construct 就好了 class NeedSingleton3 { use SingletonObject; protected $config = []; protected function __construct() { $config = [ // some config ]; $this->config = $config; } }