Search code examples
phpoopconstructor

Under what circumstances should we make a class constructor private


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?

Solution

  • 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?