Skip to content

Instantly share code, notes, and snippets.

@mAAdhaTTah
Last active March 23, 2021 11:37
Show Gist options
  • Save mAAdhaTTah/578b34c9262019d17c7f to your computer and use it in GitHub Desktop.
Save mAAdhaTTah/578b34c9262019d17c7f to your computer and use it in GitHub Desktop.
A Better WordPress Singleton
call_user_func(array(new PluginClass(__FILE__), 'boot'));
class PluginClass
{
protected static $instance = null;
public function __construct($file)
{
if (static::$instance !== null) {
throw new Exception;
}
static::$instance = $this;
}
public static function get()
{
return static::$instance;
}
}
class PluginClass
{
public static $instance = null;
public static function init()
{
if ( null === self::$instance ) {
self::$instance = new PluginClass();
self::$instance->boot();
}
return self::$instance;
}
protected function __construct()
{
// Startup
}
protected function boot()
{
// Boot
}
}
PluginClass::init();
@carloswph
Copy link

I've been using it as a trait, and checking for constraints at the same time.

https://wp-helpers.com/2021/03/23/using-the-singleton-pattern-to-deal-with-constraints/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment