Created
March 30, 2019 14:19
-
-
Save vishaldodiya/825cbc55aaef661f4250d4a11a7fc9ec to your computer and use it in GitHub Desktop.
Php Singleton Trait and using it in Class
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 | |
/** | |
* Singleton trait to implements Singleton pattern in any classes where this trait is used. | |
*/ | |
trait Singleton { | |
protected static $_instance = array(); | |
/** | |
* Protected class constructor to prevent direct object creation. | |
*/ | |
protected function __construct() { } | |
/** | |
* Prevent object cloning | |
*/ | |
final protected function __clone() { } | |
/** | |
* To return new or existing Singleton instance of the class from which it is called. | |
* As it sets to final it can't be overridden. | |
* | |
* @return object Singleton instance of the class. | |
*/ | |
final public static function get_instance() { | |
/** | |
* Returns name of the class the static method is called in. | |
*/ | |
$called_class = get_called_class(); | |
if ( ! isset( static::$_instance[ $called_class ] ) ) { | |
static::$_instance[ $called_class ] = new $called_class(); | |
} | |
return static::$_instance[ $called_class ]; | |
} | |
} | |
/** | |
* Class which uses singleton trait. | |
*/ | |
class SingletonClass { | |
use Singleton; | |
} | |
// To get the instance of the class. | |
$instance = SingletonClass::get_instance(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment