Skip to content

Instantly share code, notes, and snippets.

@wpexplorer
Last active September 7, 2020 01:33
Show Gist options
  • Save wpexplorer/23f6da2b6f1c0e52f336750a5733c945 to your computer and use it in GitHub Desktop.
Save wpexplorer/23f6da2b6f1c0e52f336750a5733c945 to your computer and use it in GitHub Desktop.
PHP Singleton Example
class My_Class {
/**
* Our single My_Class instance.
*
* @var My_Class
*/
private static $instance;
/**
* Disable instantiation.
*/
private function __construct() {
// Private to disable instantiation.
}
/**
* Disable the cloning of this class.
*
* @return void
*/
final public function __clone() {
throw new Exception( 'You\'re doing things wrong.' );
}
/**
* Disable the wakeup of this class.
*
* @return void
*/
final public function __wakeup() {
throw new Exception( 'You\'re doing things wrong.' );
}
/**
* Create or retrieve the instance of My_Class.
*
* @return My_Class
*/
public static function getInstance() {
if ( is_null( static::$instance ) ) {
static::$instance = new My_Class;
static::$instance->sample_method();
}
return static::$instance;
}
/**
* Sample method.
*
* @return void
*/
public function sample_method() {
// do things.
}
}
My_Class::getInstance();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment