36

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

I have been reading about OOP recently and came across this private constructor scenario. I did a Google search, but couldn't find anything relevant to PHP.

In PHP

  • When do we have to define a private constructor?
  • What's the purpose of using a private constructor?
  • What are the pros & cons of using a private constructor?
Community
  • 1
  • 1
Techie
  • 42,101
  • 38
  • 144
  • 232
  • 1
    This question demonstrates a scenario where you might want this: [In a PHP5 class, when does a private constructor get called?](http://stackoverflow.com/questions/26079/in-a-php5-class-when-does-a-private-constructor-get-called). – DCoder Sep 23 '12 at 14:31
  • It's private *constructor*. Change your search and you should find what you need. – Jason McCreary Sep 23 '12 at 14:33
  • Can you please add some link or description what the term *"private contractor scenario"* stands for? Also in the title you ask for Constructor, but then in the question you talk about Private Contractor. – hakre Sep 23 '12 at 16:06
  • In the title I specifically ask "When we should make the constructor Private". It contains the "private constructor" word. – Techie Sep 23 '12 at 16:12

5 Answers5

43

There are several scenarios in which you might want to make your constructor private. The common reason is that in some cases, you don't want outside code to call your constructor directly, but force it to use another method to get an instance of your class.

Singleton pattern

You only ever want a single instance of your class to exist:

class Singleton
{
    private static $instance = null;

    private function __construct()
    {
    }

    public static function getInstance()
    {
        if (self::$instance === null) {
            self::$instance = new self();
        }

        return self::$instance;
    }
}

Factory method

You want to provide several methods for creating an instance of your class, and/or you want to control the way your instances are created, because some internal knowledge of the constructor is needed to properly call it:

class Decimal
{
    private $value; // constraint: a non-empty string of digits
    private $scale; // constraint: an integer >= 0

    private function __construct($value, $scale = 0)
    {
        // Value and scale are expected to be validated here.
        // Because the constructor is private, it can only be called from within the class,
        // so we can avoid to perform validation at this step, and just trust the caller.

        $this->value = $value;
        $this->scale = $scale;
    }

    public static function zero()
    {
        return new self('0');
    }

    public static function fromString($string)
    {
        // Perform sanity checks on the string, and compute the value & scale

        // ...

        return new self($value, $scale);
    }
}

Simplified example from the BigDecimal implementation of brick/math

BenMorel
  • 30,280
  • 40
  • 163
  • 285
  • 1
    The factory approach is also useful if you want to _prevent_ an object from being instantiated, e.g. if one or more parameters are missing you can return null instead of an invalid object / instead of raising exceptions. – Optimae May 25 '18 at 17:48
36

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?

Community
  • 1
  • 1
Baba
  • 89,415
  • 27
  • 158
  • 212
4

Private constructor is used mostly in Singleton pattern, in which you don't want your class to be instantiated directly, but you want to access it via its getInstance() method.

This way you are sure nobody can call __construct() outside of the class itself.

vascowhite
  • 17,334
  • 9
  • 56
  • 73
moonwave99
  • 19,895
  • 2
  • 38
  • 62
3

Private constructor is used in two conditions

  1. When using a Singleton Pattern In this case there is only one object and the object will be created usually by a getInstance() function
  2. When using a factory function for generating objects In this case there will be multiple objects, but the object will be created by a static function for example

    $token = Token::generate();

This will generate a new Token object.

Joyce Babu
  • 15,980
  • 9
  • 57
  • 85
1

Private constructors are here to implement the singleton pattern most of time or if you want to force a factory. This pattern is useful when you want to be sure that you have only one instance of the object. it is implemented as this :

class SingletonClass{
    private static $instance=null;
    private function __construct(){}

    public static function getInstance(){
        if(self::$instance === null){
            self::$instance = new self; 

        }
        return self::$instance;
}
artragis
  • 3,797
  • 1
  • 15
  • 28