Maison > Article > développement back-end > 什么是php单例模式?
<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.<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>