php文录

code view

2019-08-26  本文已影响0人  Best博客

单例trait

<?php

trait  Singleton
{
    /**
     * @var $this
     */
    protected static $_instance;
    protected $errors = [];  //错误信息集合

    protected function __construct($defaultKey = 'defaultKey')
    {
    }

    protected function __clone()
    {
    }
    /**
     * @param string $defaultKey
     * @return $this
     */
    public static function getInstance($defaultKey='defaultKey'){
       if(!isset(self::$_instance[$defaultKey])){
          self::$_instance[$defaultKey] = new self($defaultKey);
       }
       return self::$_instance[$defaultKey];
    }
    /**
     * @return string
     */
    public function getErrors()
    {
        return implode('|', $this->errors);
    }

    /**
     *
     * @param string $error 错误信息
     * @throws Exception php全局异常对象
     * @return void
     */
    protected function setError($error)
    {
        if(!is_string($error)){
            throw new Exception("错误信息不为字符串");
        }
        $this->errors[] = $error;
    }
}

//接下来这么使用便可.
class Custorm
{
    use Singleton;
    protected function __construct($defaultKey = 'defaultKey')
    {
        //你可以在这重写你的初始化业务
    }

}


上一篇 下一篇

猜你喜欢

热点阅读