php 在 PHP5 类中,何时调用私有构造函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26079/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 21:13:26  来源:igfitidea点击:

In a PHP5 class, when does a private constructor get called?

phpoopconstructor

提问by Mark Biek

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.

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

So if I have something like this:

所以如果我有这样的事情:

class SillyDB
{
  private function __construct()
  {

  }

  public static function getConnection()
  {

  }
}

Are there any cases where __construct() is called other than if I'm doing a

除了我在做一个

new SillyDB() 

call inside the class itself?

在类本身内部调用?

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

为什么我可以从内部实例化 SillyDB 呢?

回答by Brian Warshaw

__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:

__construct()仅当您从包含私有构造函数的类的方法中调用它时才会调用它。所以对于你的单身人士,你可能有这样的方法:

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();

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.

您能够/想要从自身内部实例化类的原因是,您可以检查以确保在任何给定时间只存在一个实例。毕竟,这就是单身人士的全部意义所在。对数据库连接使用单例可确保您的应用程序一次不会进行大量数据库连接。



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

编辑:按照@emanuele-del-grande 的建议添加了 $