PHP "Singleton Mode" example to explain "go"

Source: Internet
Author: User

Transfer from:: http://www.cnblogs.com/hongfei/archive/2012/07/07/2580994.html

Suppose we need to write a class to manipulate the database and meet the following requirements:

①sqlhelper class can have only one instance (not many)
The ②sqlhelper class must be able to create this instance on its own
③ must provide this instance to the entire system on its own, in other words: multiple objects share a chunk of memory, for example, object a sets some property values, and the object B,c can also access these property values (the end example is a good illustration of the problem)

1 <?Php2Classsqlhelper{3PrivateStatic$_instance;4Public$_dbname;5Privatefunction__construct () {67}8PublicfunctionGetdbname () {9Echo$this_dbname;10}11Publicfunction Setdbname ($dbname){12$this->_dbname=$dbname;13 }14 public function clear () { 15  $this->< Span style= "color: #000000;" >_dbname); 16 }17 18 }19  $sqlHelper =< Span style= "color: #0000ff;" >new SqlHelper (); // print: Fatal error:call to private sqlhelper::__ Construct () from invalid context 20;       

The SqlHelper class above cannot create an instance from outside of its own class, because we set the constructor to private, so the new SqlHelper () is not able to use the private constructor from outside the class, and if forced, it will report the following error:
Fatal Error:call to Private sqlhelper::__construct () from invalid context
Fatal error: A private constructor was called from the context sqlhelper::__construct ()

According to the logic of the past, instantiating a class is directly outside the class using the new operator, but since the constructor is set to private, we know that a private member property or function can only be accessed within the class. So we can create a function inside the class SqlHelper (for example: getinstance ()), and it must be public, and the getinstance () function primarily instantiates the SqlHelper class
Like what:

1 <?Php2Classsqlhelper{ 3 private $_instance< Span style= "color: #000000;" >;  4 // ... Omit  5 public function< Span style= "color: #000000;" > getinstance () { $this->_instance=new SqlHelper ();  7 }< Span style= "color: #008080;" > 8 // ... Omit }10";   

But the problem came up,
① we did not instantiate the SqlHelper object before calling getinstance (), we would not be able to invoke the getinstance () function in the way of the object.
② since the object was not instantiated when calling GetInstance, the use of $this in the getinstance function would certainly have been an error (Fatal error:using $this when not in object context)
How to solve it?

Solution: We can say that the getinstance () method is set to static, according to the static definition, she can only be called by the class rather than the object, the $_instance is also set to static. So this method just fits our taste.
So we'll change the code further as follows:

1 <?Php2Classsqlhelper{3PrivateStatic$_instance;4Privatefunction__construct () {5echo "constructor is called";6}7//...... Omitted8PublicStaticfunctionGetInstance () {9if (self::$_instance===Null) {10//Self::$_instance=new SqlHelper ();//Mode OneSelf::$_instance=new self ();  way two 12 }13 return self::$_instance 14 }15 //16 }17  $sqlHelper =sqlhelper::getinstance (); // print: constructor is called 18?>  

By the getinstance function in the current memory error exists when the class class of an instance to judge, if not instantiated, and return the object handle, if any, directly return the object handle
At this point, the complete code looks like this:

1 <?Php2Classsqlhelper{3PrivateStatic$_instance;4Public$_dbname;5Privatefunction__construct () {67}8//The getinstance () method must be set to public, and this method must be called9PublicStaticfunctionGetInstance () {10//Object methods cannot access normal object properties, so $_instance needs to be set to static11if (self::$_instance===Null) {12//Self::$_instance=new SqlHelper ();//Mode OneSelf::$_instance=New self ();//Way Two14}15Return self::$_instance;16}17PublicfunctionGetdbname () {18Echo$this_dbname;19}20Publicfunction Setdbname ($dbname){21st$this->_dbname=$dbname;22}23}24//$sqlHelper =new sqlHelper ();//print: Fatal error:call to Private sqlhelper::__construct () from invalid context25$A =sqlhelper::GetInstance ();26 $A->setdbname (' database name ' 

The execution result of the above code:
Database name //$A->getdbname ();

Database name //$B->getdbname ();
Database name //$C->getdbname ();
That is, the object a,b,c is actually using the same object instance, accessing the same piece of memory area
So, even if unset ($A), objects B and C can still output the "database name" through the Getdbname () method
Unset ($A) actually simply disconnects object A from the contact between a block memory address (the address of the object's instance), which is independent of object B and object C, and can be represented in a single graph as follows

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.