Single-Case mode

Source: Internet
Author: User

/**
* Design pattern of a single case mode
* $_instance must be declared as a static private variable
* Constructors must be declared private to prevent the external program new class from losing the meaning of a singleton pattern
* The getinstance () method must be set to public, and this method must be called to return a reference to the instance
*:: operator can only access static variables and static functions
* New objects will consume memory
* Usage Scenario: The most common place is the database connection.
* Once an object is generated using singleton mode, the object can be used by many other objects.
*/
Class Mans
{
Save example instance in this property
private static $_instance;

The constructor is declared private, preventing the object from being created directly
Private Function __construct ()
{
Echo ' I was instantiated! ‘;
}

Single Case method
public static function Get_instance ()
{
Var_dump (Isset (self::$_instance));

if (!isset (self::$_instance))
{
Self::$_instance=new self ();
}
return self::$_instance;
}

Prevent users from replicating object instances
Private Function __clone ()
{
Trigger_error (' Clone is not allow ', e_user_error);
}

function test ()
{
Echo ("Test");

}
}

This is an error because the constructor method is declared as private.
$test = new Man;

The following will get the singleton object of the example class
$test = Man::get_instance ();
$test = Man::get_instance ();
$test->test ();

Copying an object will result in a e_user_error.
$test _clone = Clone $test;

Single-Case mode

Related Article

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.