How would one create a Singleton class using PHP5 classes?
相关问题
- Views base64 encoded blob in HTML with PHP
- how to define constructor for Python's new Nam
- Laravel Option Select - Default Issue
- PHP Recursively File Folder Scan Sorted by Modific
- suppress a singleton constructor in java with powe
This code can apply for any class without caring about its class name.
This article covers topic quite extensively: http://www.phptherightway.com/pages/Design-Patterns.html#singleton
You probably should add a private __clone() method to disallow cloning of an instance.
If you don't include this method the following gets possible
now
$inst1
!==$inst2
- they are not the same instance any more.All this complexity ("late static binding" ... harumph) is, to me, simply a sign of PHP's broken object/class model. If class objects were first-class objects (see Python), then "$_instance" would be a class instance variable -- a member of the class object, as opposed to a member/property of its instances, and also as opposed to shared by its descendants. In the Smalltalk world, this is the difference between a "class variable" and a "class instance variable".
In PHP, it looks to me as though we need to take to heart the guidance that patterns are a guide towards writing code -- we might perhaps think about a Singleton template, but trying to write code that inherits from an actual "Singleton" class looks misguided for PHP (though I supposed some enterprising soul could create a suitable SVN keyword).
I will continue to just code each singleton separately, using a shared template.
Notice that I'm absolutely staying OUT of the singletons-are-evil discussion, life is too short.
I liked @jose-segura method of using traits but didn't like the need to define a static variable on sub-classes. Below is a solution that avoids it by caching the instances in a static local variable to the factory method indexed by class name:
Usage is the same as @jose-segura only no need for the static variable in sub-classes.