Last active
March 23, 2021 11:37
-
-
Save mAAdhaTTah/578b34c9262019d17c7f to your computer and use it in GitHub Desktop.
A Better WordPress Singleton
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
call_user_func(array(new PluginClass(__FILE__), 'boot')); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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/