美文网首页
php实现每个类的静态方法实例化

php实现每个类的静态方法实例化

作者: 云龙789 | 来源:发表于2020-10-07 12:59 被阅读0次
    <?php
    
    /**
     * Model 基类
     * Class BaseModel
     */
    class BaseModel
    {
    
        /**
         * @var static
         */
        protected static $instance;
    
        /**
         * @var int 错误代号
         */
        protected $errCode;
    
    
        /**
         *  获取当前类
         * @return static
         */
        public static function getInstance()
        {
            if (isset(self::$instance[get_called_class()]) && self::$instance[get_called_class()] instanceof static) {
                return self::$instance[get_called_class()];
            }
            return self::$instance[get_called_class()] = new static();
        }
    
        /**
         * 获取报错代号
         * @return int
         */
        public function getErrCode()
        {
            return $this->errCode ? $this->errCode : -100;
        }
    
        /**
         * 获取错误信息
         * @return string
         */
        public function getErrMessage()
        {
            return $this->errMessage ? $this->errMessage : '没有指定错误信息';
        }
    
    
    }
    

    每个 model 类继承 BaseModel 即可

    class TestModel extends BaseGame
    {
        public function test
        {
          echo 'test'; 
        }
    }
    

    使用

    TestModel::getInstance()->test();
    TestModel::getInstance()->test();
    TestModel::getInstance()->test();
    

    不管执行多少此,都是只实例化一次

    相关文章

      网友评论

          本文标题:php实现每个类的静态方法实例化

          本文链接:https://www.haomeiwen.com/subject/mhsfpktx.html