在PHP5类中,什么时候调用私有构造函数? [英] In a PHP5 class, when does a private constructor get called?

查看:78
本文介绍了在PHP5类中,什么时候调用私有构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我正在编写一个PHP(> = 5.0)类,该类应该是单例的.我读过的所有文档都说要使类构造函数私有,所以不能直接实例化该类.

Let's say I'm writing a PHP (>= 5.0) class that's meant to be a singleton. All of the docs I've read say to make the class constructor private so the class can't be directly instantiated.

所以,如果我有这样的东西:

So if I have something like this:

class SillyDB
{
  private function __construct()
  {

  }

  public static function getConnection()
  {

  }
}

除了我在做

new SillyDB() 

在类本身内部调用?

为什么我完全允许从自身内部实例化SillyDB?

And why am I allowed to instantiate SillyDB from inside itself at all?

推荐答案

__construct()仅在您从包含私有构造函数的类的方法中调用时才被调用.因此,对于您的Singleton,您可能具有类似这样的方法:

__construct() would only be called if you called it from within a method for the class containing the private constructor. So for your Singleton, you might have a method like so:

class DBConnection
{
   private static $Connection = null;

   public static function getConnection()
   {
      if(!isset(self::$Connection))
      {
         self::$Connection = new DBConnection();
      }
      return self::$Connection;
   }

   private function __construct()
   {

   }
}

$dbConnection = DBConnection::getConnection();

您能够/将要在其内部实例化该类的原因是,您可以检查以确保在任何给定时间仅存在一个实例.毕竟,这是单例的全部要点.使用Singleton进行数据库连接可确保您的应用程序一次不会建立大量的DB连接.

The reason you are able/would want to instantiate the class from within itself is so that you can check to make sure that only one instance exists at any given time. This is the whole point of a Singleton, after all. Using a Singleton for a database connection ensures that your application is not making a ton of DB connections at a time.

根据@ emanuele-del-grande的建议,添加了$

Added $, as suggested by @emanuele-del-grande

这篇关于在PHP5类中,什么时候调用私有构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆