PHP推延靜態繫結

來源:互聯網
上載者:User
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;    }}

然後是各個邏輯子類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);

此類$good 為
object(BaseModel)#1 (0) {}

非需要的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;    }}

這時的$good 即為
object(GoodModel)#1 (0) {}


其實也可用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;    }}
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.