Maison > Article > développement back-end > php入门2 单例模式
单例模式:
模式:提供创建的静态方法或在构造函数中创建。常用是静态方法。
1.构造函数私有访问属性
2.静态的指向本类的指针
3.静态的创建自身的方法
以下是php中的实现,getinstall理论上应该加上线程同步,暂未写。
<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></span></code>').addClass('pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i ').text(i)); }; $numbering.fadeIn(1700); }); });
以上就介绍了 php入门2 单例模式,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。