PHP延迟静态绑定
最近项目中遇到这样一个case,感觉所有的Model类都须是单例性能更高.因为所有的model皆继承统一父类BaseModel,所以在BaseModel中添加控制单例的代码,简单演示如下:
/*基类*/class BaseModel{ private static $instance = null; public static function instance() { if (empty(self::$instance)) { self::$instance = new self(); } return self::$instance; }}
/*商品类*/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);
object(BaseModel)#1 (0) {}
/*基类*/class BaseModel{ private static $instance = null; public static function instance() { if (empty(self::$instance)) { self::$instance = new static(); } return self::$instance; }}
object(GoodModel)#1 (0) {}
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; }}