Last active
September 7, 2020 01:33
-
-
Save wpexplorer/23f6da2b6f1c0e52f336750a5733c945 to your computer and use it in GitHub Desktop.
PHP Singleton Example
This file contains hidden or 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 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