回覆內容:
其實單例模式,說白了就是說一個類別只能實例化一次。但是我們要如何在這個實例化一次上面做文章呢。其實有個突破口就是__construct()這個魔術方法。這個方法就代表如果類別實例化的時候,就會自動執行這個方法。然後如果我把這個方法變成保護或私有的,會是什麼效果呢。
<code class="language-text"><?php
class test{
protected function __construct(){
}
}
$test = new test();
?>
</code>
登入後複製
<code class="language-php"><span class="x">static function getInstance($class, $param = array())</span>
<span class="x">{</span>
<span class="x"> if (!isset($obj[$class])) {</span>
<span class="x"> $obj[$class] = new $class($param);</span>
<span class="x"> }</span>
<span class="x"> return $obj[$class];</span>
<span class="x">}</span>
<span class="x">在实例化一个类时,先判断是否有这个类的实例,如果有就不实例化,反之就实例化一个</span>
</code>
登入後複製
厲害 樓主無敵
Talk is cheap,show you my code.
最簡單的PHP單例模式的類別:
<code class="language-php"><span class="x">class TestInstance</span>
<span class="x">{</span>
<span class="x"> public static $_instance = null;</span>
<span class="x"> //为了防止外部new这个类,所以构造方法用protected,这是单例模式的关键之处</span>
<span class="x"> protected function __Construct()</span>
<span class="x"> {</span>
<span class="x"> echo 'Instance,Instance,Instance..........';</span>
<span class="x"> }</span>
<span class="x"> //用一个静态变量存储类的实例,只有第一次实例化的时候才赋值,以后都直接给出静态实例</span>
<span class="x"> public static function getInstance()</span>
<span class="x"> {</span>
<span class="x"> if(!isset(self::$_instance)){</span>
<span class="x"> self::$_instance = new static();</span>
<span class="x"> }</span>
<span class="x"> return self::$_instance;</span>
<span class="x"> }</span>
<span class="x">}</span>
</code>
登入後複製