PHP Object-oriented-singleton mode
PHP Object-oriented-singleton mode
Guaranteed class has only one instance
1. How can a class be resolved 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. However, it can be instantiated within a class.
Add a public static method that calls the method through the class and can perform a 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 executes, so we can restrict the user to get the object's operation by perfecting the logic inside the method.
3. In the above method, use such logic: each time the execution of the judgment, to determine whether the class has instantiated the object, if instantiated, then directly return the instantiation of the good object. If it is not instantiated, a new one is instantiated and then returned.
How to judge?
When the object is instantiated, save it.
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. Clones can also get new objects, so you need to restrict 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;
}
}
http://www.bkjia.com/PHPjc/871193.html www.bkjia.com true http://www.bkjia.com/PHPjc/871193.html techarticle PHP Object-oriented-singleton mode PHP Object-oriented-singleton mode guarantees that the class has only one instance 1. How can I solve a class that can be instantiated indefinitely? New, you can instantiate it once ...