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
Supports Multiple Objects with 1 line per class:
This method will enforce singletons on any class you wish, al you have to do is add 1 method to the class you wish to make a singleton and this will do it for you.
This also stores objects in a "SingleTonBase" class so you can debug all your objects that you have used in your system by recursing the
SingleTonBase
objects.Create a file called SingletonBase.php and include it in root of your script!
The code is
Then for any class you want to make a singleton just add this small single method.
Here is a small example:
And you can just add this singleton function in any class you have and it will only create 1 instance per class.
NOTE: You should always make the __construct private to eliminate the use of new Class(); instantiations.
PHP 5.3 allows the creation of an inheritable Singleton class via late static binding:
This solves the problem, that prior to PHP 5.3 any class that extended a Singleton would produce an instance of its parent class instead of its own.
Now you can do:
And $foo will be an instance of Foobar instead of an instance of Singleton.
To use:
$fact == $fact2;
But:
Throws an error.
See http://php.net/manual/en/language.variables.scope.php#language.variables.scope.static to understand static variable scopes and why setting
static $inst = null;
works.Unfortunately Inwdr's answer breaks when there are multiple subclasses.
Here is a correct inheritable Singleton base class.
Test code:
You don't really need to use Singleton pattern because it's considered to be an antipattern. Basically there is a lot of reasons to not to implement this pattern at all. Read this to start with: Best practice on PHP singleton classes.
If after all you still think you need to use Singleton pattern then we could write a class that will allow us to get Singleton functionality by extending our SingletonClassVendor abstract class.
This is what I came with to solve this problem.
Use example:
Just to prove that it works as expected:
Database class that checks if there is any existing database instance it will return previous instance.
Ref http://www.phptechi.com/php-singleton-design-patterns-example.html