亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在PHP 5中創建單例設計模式

在PHP 5中創建單例設計模式

慕桂英4014372 2019-06-24 10:44:40
在PHP 5中創建單例設計模式如何使用PHP 5類創建Singleton類?
查看完整描述

3 回答

?
MMTTMM

TA貢獻1869條經驗 獲得超4個贊

PHP 5.3允許通過后期靜態綁定創建可繼承的Singleton類:

class Singleton{
    protected static $instance = null;

    protected function __construct()
    {
        //Thou shalt not construct that which is unconstructable!
    }

    protected function __clone()
    {
        //Me not like clones! Me smash clones!
    }

    public static function getInstance()
    {
        if (!isset(static::$instance)) {
            static::$instance = new static;
        }
        return static::$instance;
    }}

這解決了這個問題,在PHP5.3之前,任何擴展Singleton的類都會生成它的父類的實例,而不是它自己的實例。

現在你可以:

class Foobar extends Singleton {};$foo = Foobar::getInstance();

$foo將是Foobar的實例,而不是Singleton的實例。


查看完整回答
反對 回復 2019-06-24
  • 3 回答
  • 0 關注
  • 623 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號