Singleton pattern restricts the instantiation of a class to a single instance.
Private keyword hides the class constructor for outside.
classMyClass{
privatestatic $instance;
public $userId;
/**
* Private constructor
* The class cannot be intialized from outside
*/privatefunction__construct(){}
/**
* Static methods or properties can be access
* only as part of a class itself
*/publicstaticfunctiongetInstance(){
if (self::$instance === null) {
self::$instance = newself(); // Look Here
}
returnself::$instance;
}
}
// $obj = new MyClass(); // Fatal Error
$obj = MyClass::getInstance();
$obj->userId = 2;
$obj2 = MyClass::getInstance();
echo $obj->userId; // 2
Example
Prevent class from being extended, declare it as final.
Prevent second instance of the class (private _clone() or __wake()).
// App.phpdeclare(strict_types=1);
namespaceDesignPatterns\Singleton;
finalclassApp{
privatestatic $instance;
/**
* get the instance via lazy initialization
* intialization created on first usage
*/publicstaticfunctiongetInstance() : App{
if (! static::$instance) {
static::$instance = newself();
}
returnstatic::$instance;
}
/**
* prevent outside multiple instantiantion
* getInstance() must be used instead
*/privatefunction__construct(){
}
/**
* prevent the instance from being clone
* which will create a second instance of it
*/privatefunction__clone(){
}
/**
* prevent the instance from being unserialized
* which will create a second instance of it
*/privatefunction__wakeup(){
}
}