Skip to content

Instantly share code, notes, and snippets.

@broskees
Last active July 20, 2023 16:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save broskees/b932302414c98b5ad077d270e52fd6e7 to your computer and use it in GitHub Desktop.
Save broskees/b932302414c98b5ad077d270e52fd6e7 to your computer and use it in GitHub Desktop.
PHP — Anonymous Singleton Class
<?php
$singleton = get_class(
new class
{
protected static $instance;
public static function getInstance()
{
if (! isset(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
public function someMethod()
{
// do something
}
public function anotherMethod()
{
// do something else
}
}
);
$singleton::getInstance()->someMethod();
$singleton::getInstance()->anotherMethod();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment