Php object-oriented-Singleton mode. Php object-oriented-Singleton mode ensures that the class has only one instance. 1. how can I solve the problem that a class can be infinitely instantiated? New, you can instantiate a Php object-oriented-Singleton mode
Php object-oriented-Singleton mode
Ensure that the class has only one instance
1. how can a class be infinitely instantiated?
New, can be instantiated once, how to limit, the user can not be infinitely new?
Privatize the constructor. All external new operations fail.
Class MySQLDB
{
Private function _ construct ()
{
}
}
2. Once the constructor method is private, it means that the class cannot be instantiated outside the class. But it can be instantiated in the class.
Add a public static method to call the method through a class, and execute the new operation in the method.
Class MySQLDB
{
Private function _ construct ()
{
}
Public static function getInstance ()
{
Return new MySQLDB;
}
}
$ O = MySQLDB: getInstance ();
At this time, the user needs the objects of this class, and the code in the method will be executed. Therefore, we can improve the logic in the method to limit the operations on the user to get the objects.
3. in the preceding method, the logic is used to determine whether the class has instantiated an object during each execution. if the class is instantiated, the instantiated object is directly returned. If it is not instantiated, a new one will be instantiated and a new one will be returned.
How to judge?
This object is saved when it is instantiated.
Example:
Class MySQLDB
{
Private static $ instance;
Private function _ construct ()
{
}
Public static function getInstance ()
{
If (! Self: $ instance instanceof self)
{
Self: $ instance = new self;
}
Return self: $ instance;
}
}
4. cloning can also get new objects, so you need to restrict cloning.
Private_clone () method
Class MySQLDB
{
Private static $ instance;
Private function _ construct ()
{
}
Private function _ clone ()
{
}
Public static function getInstance ()
{
If (! Self: $ instance instanceof self)
{
Self: $ instance = new self;
}
Return self: $ instance;
}
}
Solution-Singleton mode Php object-oriented-Singleton mode ensures that the class has only one instance. 1. how can I solve the problem that a class can be infinitely instantiated? New, it can be instantiated once...