2011年8月12日 星期五

php 單例設計模式

單例設計模式 今天在網路上看到的一個名詞 說穿了它就是例用static這個關鍵字 其實static早就php4就已經存在了 但很少看到討論它的功能 再順便討論一下吧 ```php function test() { static $a; if ($a == FALSE) { $a = 1; } else { $a++; } echo $a; } test(); //輸出 1 test(); //輸出 2 test(); //輸出 3 test(); //輸出 4 /* 所以當你指定了變數為static時 它就不會因為function執行結束後而將變數回收 所以我們這個例用這個方法來實現單例設計模式 */ class Test { function instance() { static $instance; if ($instance == FALSE) { $instance = new Test(); } return $instance; } } $test =& Test::instance(); $test2 =& Test::instance(); $test3 =& Test::instance(); /* 這樣$test,$test2,$test3都會指向同一個物件 以上為PHP4的寫法 PHP4必須帶參考才能將物件指到同一下 那php5怎麼寫呢? */ class Test { static private $instance; static public function instance() { if (self::$instance == FALSE) { self::$instance = new self; } return self::$instance; } } $test = Test::instance(); /* PHP5的CLASS支援這種寫法當然要用這種寫法了啊! 雖然採用PHP4的寫法也行.... 但新的東西總是要用一下的是不是 */ ```

1 則留言:

  1. 很抱歉打擾您

    小弟是php新手工程師
    針對這篇文章分享的內容有理解的障礙

    比方說php4的寫法
    小弟就可以很直覺的了解程式運作的邏輯
    但php5的部份我就看不懂了

    不好請您直接指導
    不知是否能指教小弟這部份能使用到的
    是那些觀念或技術
    能否給小弟一些關鍵字
    方便做進一步的學習了解

    謝謝

    回覆刪除