If singleton pattern is used that's when the class constructor should be declared as private. This protects the object creation using the keyword new. In other way this is to ensure one instance for that class everywhere in one execution.
Following is a simple example of private constructor method in a class:
Now lets see what happens if the constructor is public instead of private. Actually this will allow object creation using the keyword new. When an object is instantiated then it does not guarantee of a single object of a class in an execution. The design patter is not singleton then.
Let check the following code snippet
Following is a simple example of private constructor method in a class:
class Logging { private static $instance; private function __construct() { } public static function getInstance(){ if(!isset(self::$instance)){ self::$instance = new Logging(); } return self::$instance; } } $firstObj = Logging::getInstance(); $secondObj = Logging::getInstance(); if($firstObj === $secondObj) { echo 'Both objects are same'; } else{ echo 'Both objects are not same'; }
Output
Both objects are same
Now lets see what happens if the constructor is public instead of private. Actually this will allow object creation using the keyword new. When an object is instantiated then it does not guarantee of a single object of a class in an execution. The design patter is not singleton then.
Let check the following code snippet
class Logging { private static $instance; public function __construct() { } public static function getInstance(){ if(!isset(self::$instance)){ self::$instance = new Logging(); } return self::$instance; } } $firstObj = Logging::getInstance(); $secondObj = new Logging; if($firstObj === $secondObj) { echo 'Both objects are same'; } else{ echo 'Both objects are not same'; }
Output
Both objects are not same
Comments
Post a Comment