Home  >  Article  >  Backend Development  >  What is php singleton pattern?

What is php singleton pattern?

WBOY
WBOYOriginal
2016-12-01 00:01:161125browse

Reply content:

In fact, the singleton model, to put it bluntly, means that a class can only be instantiated once. But how do we make a fuss about this instantiation? In fact, a breakthrough is the magic method __construct(). This method means that if the class is instantiated, this method will be automatically executed. Then if I make this method protected or private, what will be the effect?
<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>
Awesome, the host is invincible Talk is cheap,show you my code.

The simplest PHP singleton mode class:
<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>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn