Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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()   {    } } 

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?

like image 629
Mark Biek Avatar asked Aug 25 '08 14:08

Mark Biek


People also ask

How are private constructors called?

getDeclaredConstructor() can be used to obtain the constructor object for the private constructor of the class. The parameter for this method is a Class object array that contains the formal parameter types of the constructor.

What happens if constructor of class A is called private?

Private constructor means a user cannot directly instantiate a class. Instead, you can create objects using something like the Named Constructor Idiom, where you have static class functions that can create and return instances of a class.

When a class has a private constructor?

Private constructors are used to prevent creating instances of a class when there are no instance fields or methods, such as the Math class, or when a method is called to obtain an instance of a class. If all the methods in the class are static, consider making the complete class static.

How are private constructors called in Java?

A private constructor cannot be directly called by client objects of the class. They can only be called internally by methods of the class (even private). You can have a private constructor with one or more parameters. You cannot have return type of the constructor be primitive boolean.


1 Answers

__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

like image 117
Brian Warshaw Avatar answered Sep 23 '22 07:09

Brian Warshaw