Single case pattern:
Pattern: Provide static method of creation or create in constructor. Commonly used are static methods.
1. Constructor private access properties
2. Static pointer to this class
3. Staticly create your own method
The following is the implementation in PHP. In theory, getinstall should add thread synchronization, but it has not been written yet.
<code><span><span><?php</span><span><span>class</span><span>myclass</span>{</span><span>public</span><span>static</span><span>$mydata1</span>=<span>NULL</span>; <span>private</span><span><span>function</span><span>__construct</span><span>()</span>{</span><span>echo</span><span>"构造函数<br>"</span>; } <span>public</span><span>static</span><span><span>function</span><span>getinstall</span><span>()</span> {</span><span>if</span> ( <span>self</span>::<span>$mydata1</span>==<span>null</span>) { <span>echo</span><span>"创建对象<br>"</span>; <span>self</span>::<span>$mydata1</span> = <span>new</span> myclass(); } <span>return</span><span>self</span>::<span>$mydata1</span>; } <span>public</span><span><span>function</span><span>test</span><span>()</span> {</span><span>echo</span><span>"hello2<br>"</span>; } } <span>$f</span> = myclass::getinstall(); <span>$f</span>->test(); <span>$f2</span> = myclass::getinstall(); <span>$f2</span>->test(); <span>?></span></span></code>
The above introduces the singleton mode of Getting Started with PHP 2, including various aspects. I hope it will be helpful to friends who are interested in PHP tutorials.