Heim  >  Artikel  >  Backend-Entwicklung  >  PHP延迟静态绑定

PHP延迟静态绑定

巴扎黑
巴扎黑Original
2016-11-11 13:13:50889Durchsuche

最近项目中遇到这样一个case,感觉所有的Model类都须是单例性能更高.因为所有的model皆继承统一父类BaseModel,所以在BaseModel中添加控制单例的代码,简单演示如下: 

Java代码  

/*基类*/  
class BaseModel  
{  
  
    private static $instance = null;  
  
    public static function instance()  
    {  
  
        if (empty(self::$instance)) {  
  
            self::$instance = new self();  
        }  
  
        return self::$instance;  
    }  
}

然后是各个逻辑子类Model 

Java代码  

/*商品类*/  
class GoodModel extends BaseModel{  
  
    public function getInfoById($goodId){  
  
        return array(  
            'id'=>$goodId,  
            'name'=>'小苹果',  
            'logo'=>'http://t3.qlogo.cn/mbloghead/65518bb9e5287fcd5864/180'  
        );  
    }  
}  
  
################################################################  
$good = GoodModel::instance();  
  
var_dump($good);


此类$good 为 

Java代码  

object(BaseModel)#1 (0) {  
}


非需要的GoodModel 


这是就需要介绍self 

self::调用的变量只是该类的 即使该类被继承 变量被重写 调用父类里的函数 self::调用的变量还是输出父类的变量值 而不会输出被重写的值 


所以需要采用static关键字延迟静态绑定,static代表了子类 
代码如下 

Java代码  

/*基类*/  

class BaseModel  
{  
  
    private static $instance = null;  
  
    public static function instance()  
    {  
  
        if (empty(self::$instance)) {  
  
            self::$instance = new static();  
        }  
  
        return self::$instance;  
    }  
}

这时的$good 即为 

Java代码  

object(GoodModel)#1 (0) {  
}

其实也可用get_called_class函数来解决上面的问题,代码如下 

Java代码  

class BaseModel  
{  
  
    private static $instance = null;  
  
    public static function instance()  
    {  
  
        if (empty(self::$instance)) {  
  
            $className = get_called_class();  
            self::$instance = new $className();  
        }  
  
        return self::$instance;  
    }  
}


Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn