Created
March 10, 2016 20:59
-
-
Save davidmyersdev/ca96743c4ba896254f96 to your computer and use it in GitHub Desktop.
A DRY implementation for the Singleton design pattern in PHP.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
trait Singleton | |
{ | |
/** | |
* The instance of our Singleton object. | |
*/ | |
protected static $instance; | |
/** | |
* The public method to return an instance of the Singleton object. | |
* | |
* @return void | |
*/ | |
public static function getInstance() | |
{ | |
if (null === static::$instance) | |
{ | |
static::$instance = new static(); | |
} | |
return static::$instance; | |
} | |
/** | |
* Make sure the constructor is protected so we can't accidentally create | |
* a new instance of the object. | |
* | |
* @return void | |
*/ | |
protected function __construct() | |
{ | |
} | |
/** | |
* Disable external usage of __clone() to return a new instance. | |
*/ | |
private function __clone() | |
{ | |
} | |
/** | |
* Disable external usage of __wakeup() to return a new instance. | |
*/ | |
private function __wakeup() | |
{ | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Implementation is pretty simple at this point:
You can now get the object instance via the public Singleton
getInstance()
method.That's it! Enjoy an easy way to implement the Singleton design pattern without repeating code.