Home > Backend Development > PHP Tutorial > PHP推延静态绑定

PHP推延静态绑定

WBOY
Release: 2016-06-13 12:13:28
Original
793 people have browsed it

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;    }}
Copy after login

然后是各个逻辑子类Model
/*商品类*/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);
Copy after login

此类$good 为
object(BaseModel)#1 (0) {}
Copy after login

非需要的GoodModel


这是就需要介绍self

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


所以需要采用static关键字延迟静态绑定,static代表了子类
代码如下
/*基类*/class BaseModel{    private static $instance = null;    public static function instance()    {        if (empty(self::$instance)) {            self::$instance = new static();        }        return self::$instance;    }}
Copy after login

这时的$good 即为
object(GoodModel)#1 (0) {}
Copy after login


其实也可用get_called_class函数来解决上面的问题,代码如下
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;    }}
Copy after login

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template