search

Home  >  Q&A  >  body text

PHP的单例模式有什么用?跟直接用类本身有什么区别呢?

PHP的单例模式是为了避免重复创建对象带来的资源消耗,那么跟直接用类名::静态成员变量 ,类名::静态成员属性有什么区别呢?另外,php是以页面为执行为执行单位的,执行完一个页面后该页面就从内存里被销毁,那么如何在不借助数据库的前提下,保存一个生存期等于整合程序执行期的变量呢?

phpcn_u391phpcn_u3912929 days ago1091

reply all(2)I'll reply

  • 数据分析师

    数据分析师2017-10-01 00:21:00

    What is the use of PHP’s singleton mode? What is the difference from using the class itself directly? -PHP Chinese website Q&A-What is the use of PHP’s singleton mode? What is the difference from using the class itself directly? -PHP Chinese website Q&A

    Let’s take a look and learn.

    reply
    0
  • 阿神

    阿神2017-02-15 15:34:33

    单例模式可以确保这个类在全局只能有一个实例,因为它的实例是由自己保存,在类的外部也无法对该类进行实例化。而题主所说的其他方法都不容易达到这个目的。

    第二个问题说php是以页面为执行单位的,我理解意思应该是以请求为执行单位的吧?每次请求过来,php解释器会解释源代码而后执行,如果需要保存这种跨请求的变量,可以使用session保存起来,对于类实例这样的变量,也可以先序列化再保存到session中,下次请求只需要反序列化就可以了。

    reply
    0
  • Cancelreply