In a PHP5 Class, When Does a Private Constructor Get Called

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

When is called private constructor in PHP5 class?

A private constructor makes sure you cannot instanciate this class outside of itself.

So calling

$obj = new SillyDB();

would result in an error.

This technique is usually used when creating singleton classes.

This stone old comment in the manual describes it pretty well: http://www.php.net/manual/de/language.oop5.decon.php#80314

You have a static method inside the class that manages a single instance of the class which can be retreived through the method.

Under what circumstances should we make a class constructor private

When do we have to define a private constructor?

class smt 
{
private static $instance;
private function __construct() {
}
public static function get_instance() {
{
if (! self::$instance)
self::$instance = new smt();
return self::$instance;
}
}
}

What's the purpose of using a private constructor?

It ensures that there can be only one instance of a Class and provides a global access point to that instance and this is common with The Singleton Pattern.

What are the pros & cons of using a private constructor?

  • Are Singletons really that bad?

  • What is so bad about singletons?

extending class with private constructor in php different from version 5.1 to 5.4

It is the bug. You could fix your code like this (PHP > PHP5.3):

class MyClass {

private static $instance;

private function __construct() {

}

static function getInstance() {
if (isset(self::$instance)) {
return self::$instance;
} else {
self::$instance = new static();
return self::$instance;
}
}

}

class ExtendedClass Extends MyClass {
}


Related Topics



Leave a reply



Submit