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

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


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

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