Skip to content

Instantly share code, notes, and snippets.

@EkoJR
Created December 14, 2021 21:26
Show Gist options
  • Save EkoJR/68d52a6aa1b900de91526b6ca533c88b to your computer and use it in GitHub Desktop.
Save EkoJR/68d52a6aa1b900de91526b6ca533c88b to your computer and use it in GitHub Desktop.
Designed to be called as a singleton get_instance() or standard class constructor.
class singleton_constructor {
public $foo = 'foo';
public $bar = 'bar';
public $foobar;
private static $instance = null;
private function __clone() {}
private function __sleep() {}
private function __wakeup() {}
public static function get_instance() {
if ( null === self::$instance ) {
self::$instance = new self();
}
return self::$instance;
}
public function __construct( $initial_text ) {
if ( null !== self::$instance ) {
// Runs when there's a pre-existing instance.
$this->foo = self::$instance->foo;
$this->bar = self::$instance->bar;
$this->foobar = self::$instance->foo . self::$instance->bar;
} else {
// Runs when it's a new instance.
$this->foobar = $initial_text;
}
self::$instance = $this;
// Run on every instance.
$this->output( $this->foobar );
}
public function output( $text ) {
echo $text;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment