Recently went to the interview, encountered a singleton model of the problem, learned something previously did not think of things, although the interview failed, but still good oh. For everyone to share.
PHP is run as a process, we ignore the problem of multithreading, do not have to lock the attributes. A common singleton pattern class.
Scenario where a singleton mode runs, sometimes we may have only one instance of a class running in a process.
The common singleton pattern is written in this way.
Class singleclass{
private static $instance = null;
Construction method
Private Function __construct () {
echo "New obj";
}
Get instance
public static function getinstance () {
if (Empty (self:: $instance)) {
Self:: $instance = new self ();
}
Return self:: $instance;
}
}
$SC = new Singleclass ();//Error
$SC = Singleclass::getinstance ();//Create Singleton mode
It doesn't seem to be a problem, but what if we clone it?
(object replication can be done by using the Clone keyword)
$SC 2 = Clone $sc;//clone a new object
Var_dump ($SC, $SC 2);
Output:
New Objclass singleclass#1 (0) {
}
Class Singleclass#2 (0) {
}
This class actually produces a new object under the same process,
How to avoid this problem.
Class singleclass{
private static $instance = null;
Construction method
Private Function __construct () {
echo "New obj";
}
Get instance
public static function getinstance () {
if (Empty (self:: $instance)) {
Self:: $instance = new self ();
}
Return self:: $instance;
}
private function __clone(){ echo "clone";}
}
$SC = new Singleclass ();//Error
$SC = Singleclass::getinstance ();//Create Singleton mode
$SC 2 = Clone $sc;//clone a new object
Var_dump ($SC, $SC 2);
The running code will then error.
New objphp Fatal Error:call to Private singleclass::__clone () from context ' In/users/kang/documents/phpproject/test/te St.php on line
This is the better singleton pattern in PHP.
What is the nature of the problem? The way PHP creates objects.
PHP object in the PHP source code inside the representation of the source code
The way PHP creates objects, as already mentioned above.
1 new classname (); 2 Clone Object
The third kind, by reflection
$reflect = new Reflectionclass ($SC);
$method = $reflect->getmethod ("getinstance");
Var_dump ($method->invoke ($SC));
How to create PHP objects from PHP singleton mode