PHP Single-instance mode

Source: Internet
Author: User

/***********************************************/
/****************** single-row mode *********************/
/***********************************************/


1.1 Single-row mode

Singleton mode: A class can have only one instance

Constructor non-public

Three main principles:

1: constructor needs to be marked as non-public (it can only be instantiated by itself)

2: A static member variable that holds an instance of the class $_instance

3: Have a public static method that accesses this instance

/**********************************************************/

<?php

Class instance{

To save a static variable for a class instance

private static $_instance;

Constructor declared as non-public

Private Function __construct () {

}

A public static method that accesses this instance

public static function getinstance () {

Determine if a class is being instantiated

if (! ( Self::$_instance instanceof Self)) {

Static variable = Instantiate class itself

Self::$_instance = new self ();

}

return self::$_instance;
}

Define a method yourself

Public Function test () {

echo "Test";

}

Prevent users from replicating object instances

Public Function __clone () {

The Trigger_error () function creates a user-defined error message

Trigger_error (' Clone is not allow ', e_user_error);

}

}

This is an error because the constructor method is declared as private.

$test = new Example;

The following will get the singleton object of the instance class

$test = Instance::getinstance ();

$test->test ();

Copying an object will result in a e_user_error.

$test _clone = Clone $test;

?>

PHP Single-instance 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.