PHP Object-oriented-singleton mode

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.