/***********************************************/
/****************** 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