Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Php Singleton Trait and using it in Class
<?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
You can’t perform that action at this time.