PHP Object-oriented-singleton mode
Guaranteed class has only one instance
1. How can a class be solved with infinite instantiation?
New, you can instantiate once, how to limit, the user can not unlimited new?
Privatize the construction method. All external new operations fail
Class MySQLdb
{
Private Function __construct ()
{
}
}
2. Once the construction method is privatized, it means that the class cannot be instantiated out of class. But can be instantiated within a class.
Add a public static method that calls the method through the class and can run the new operation within the method.
Class MySQLdb
{
Private Function __construct ()
{
}
public static function getinstance ()
{
return new MySQLdb;
}
}
$o = Mysqldb::getinstance ();
At this point, the user needs the object of the class, the code inside the method will run, so we can restrict the user to get the object's operation through the logic inside the good method.
3. In the above method, use this logic: each run-time inference to infer whether the class has instantiated the object, assuming that the instantiation, then directly return the instantiation of the good object. Assuming there is no instantiation, a new one is instantiated and then returned.
How to infer?
When the object is instantiated, save it.
Examples:
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. Clones are also able to obtain new objects and therefore need to limit cloning.
Privatization __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;
}
}
PHP Object-oriented-singleton mode