Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@vishaldodiya
Created March 30, 2019 14:19
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vishaldodiya/825cbc55aaef661f4250d4a11a7fc9ec to your computer and use it in GitHub Desktop.
Save vishaldodiya/825cbc55aaef661f4250d4a11a7fc9ec to your computer and use it in GitHub Desktop.
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