Skip to content

Instantly share code, notes, and snippets.

@kamalahmed
Last active March 6, 2020 18:06
Show Gist options
  • Save kamalahmed/6ca7e3c6868a3168d1732c9ac534efa7 to your computer and use it in GitHub Desktop.
Save kamalahmed/6ca7e3c6868a3168d1732c9ac534efa7 to your computer and use it in GitHub Desktop.
Singleton Design Pattern
<?php
final class Sample_Plugin {
private static $instance;
// prevent direct instantiation
private function __construct() {
}
public static function init(){
// lets return the instance if we have already
if (isset( self::$instance)) return self::$instance;
//at this point, we do not have instance ready, so, let's initialize it, store it and return it.
self::$instance = new self;
//....other neccessary stuff and at the end, return the instance
return self::$instance;
}
// optionally, it is best practice to prevent cloning and serialization by return exception from __clone and __wakeup
}
// helper function to get a true instance of Sample_Plugin
function sample_plugin() {
return Sample_Plugin::init();
}
// lets run the plugin
sample_plugin();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment