From the php Singleton mode to the creation method of php Objects, I recently went to the interview. I encountered a problem in Singleton mode and learned something I did not expect. Although the interview failed, but it's good. Share with you.
Php runs as a process. we ignore the problem of multithreading and do not need to lock the attribute. Common Singleton mode classes.
In a singleton mode, sometimes a class in a process only runs on one instance.
This is the common singleton mode.
Class SingleClass {
Private static $ instance = null;
// Constructor
Private function _ construct (){
Echo "new obj ";
}
// Obtain the instance
Public static function getInstance (){
If (empty (self: $ instance )){
Self: $ instance = new self ();
}
Return self: $ instance;
}
}
// $ SC = new SingleClass (); // error
$ SC = SingleClass: getInstance (); // creates the SingleClass mode.
It looks okay, but what if we clone it?
(Object replication can be completed by using the clone keyword)
$ Sc2 = clone $ SC; // clone a new object
Var_dump ($ SC, $ sc2 );
Output:
New objclass SingleClass #1 (0 ){
}
Class SingleClass #2 (0 ){
}
In the same process, this class actually produces new objects,
How can we avoid this problem.
Class SingleClass {
Private static $ instance = null;
// Constructor
Private function _ construct (){
Echo "new obj ";
}
// Obtain the 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 (); // creates the SingleClass mode.
$ Sc2 = clone $ SC; // clone a new object
// Var_dump ($ SC, $ sc2 );
An error is reported when you run the code.
New objPHP Fatal error: Call to private SingleClass :__ clone () from context ''in/Users/kang/Documents/phpProject/test. php on line
This is a good Singleton mode in php.
What is the essence of this question? Php creates an object.
For the representation of php Objects in php source code, see source code.
Php object creation method, as mentioned above.
1 new classname (); 2 clone object
Third, through reflection
$ Reflect = new ReflectionClass ($ SC );
$ Method = $ reflect-> getMethod ("getInstance ");
Var_dump ($ method-> invoke ($ SC ));