Home  >  Article  >  Backend Development  >  每天一记之php单例模式实现

每天一记之php单例模式实现

WBOY
WBOYOriginal
2016-06-13 12:35:20837browse

每日一记之php单例模式实现

单例模式,顾名思义就是只需要只有一个实例化对象, 在软件的设计中,单例模式是非常常用的。实例化一次,节省了大量的资源,而且单例模式在一定程度上可以替换类中引入全局变量而导致的bug。因为全局变量将类捆绑于特定的环境中。破坏了封装,这样的类很难被其他的应用程序所通用。使用单例模式则能够将类更好的组织,并且复用。

下面一起来看看php中单例模式的实现





调用代码

$singleton = Singleton::getInstance();
$singleton2 = Singleton::getInstance();


var_dump($singleton === $singleton2);



在上面的调用代码中,在最后将打印true, 这样我们就简单的实现了单例模式。




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