Basic Programming: About the Singleton mode, Daniel comes in ~~~ & Lt ;? PhpclassExample {& nbsp; // Save the class instance in this attribute & nbsp; privatestatic $ instance; & nbsp; // The constructor declaration is private, prevent basic direct programming: Regarding the Singleton mode, Daniel comes in ~~~
Class Example
{
// Save the class instance in this attribute
Private static $ instance;
// The constructor is declared as private to prevent direct object creation.
Private function _ construct ()
{
Echo 'I am constructed
';
}
// Singleton method
Public static function singleton ()
{
If (! Isset (self: $ instance ))
{
$ C =__ CLASS __;
Self: $ instance = new $ c;
}
Return self: $ instance;
}
// Common methods in the Example class
Public function bark ()
{
Echo 'Woof! ';
}
// Prevents users from copying object instances
Public function _ clone ()
{
Trigger_error ('Clone is not allowed. ', E_USER_ERROR );
}
Public function destroy ()
{
Unset (self: $ instance );
}
}
// This write method will fail because the constructor is declared as private.
// $ Test = new Example;
// The following is a singleton object of the Example class.
$ Test = Example: singleton ();
$ Test-> bark ();
// Copying an object will result in an E_USER_ERROR.
// $ Test_clone = clone $ test;
$ B = Example: singleton ();
$ B-> destroy ();
?>
Original article: http://www.php.net/manual/zh/language.oop5.patterns.php
Here I want to ask:
1) $ B = Example: singleton (); whether to generate a new object or
Both $ test and $ B point to the generated object Example: singleton?
2) Why does my destroy () method fail? There is no way to destroy the Example: singleton () object or change it to null,
Does this change $ test and $ B to null at the same time?
------ Solution --------------------
Private function _ clone: the release of a singleton should not be performed by destructor. The concept is completely obfuscated. an independent public static interface should be provided to release the singleton object.
1. same object
2. as mentioned above, it will not become null. you should not use the two variables because the object is referenced.
------ Solution --------------------
I wrote a small test.
PHP code
------ Solution --------------------
I also tried it myself. an object is referenced by itself, and a variable is referenced by two references. So null and $ I at the beginning are like this. I don't know if it is correct, but it does not matter.
------ Solution --------------------
Discussion
2) Why does my destroy () method fail? There is no way to destroy the Example: singleton () object or change it to null,