Skip to content

Instantly share code, notes, and snippets.

@kanian
Last active March 8, 2019 22:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kanian/f410453456bac9002aeed4b25f50155e to your computer and use it in GitHub Desktop.
Save kanian/f410453456bac9002aeed4b25f50155e to your computer and use it in GitHub Desktop.
<?php
function singletonize(\Closure $func)
{
$singled = new class($func)
{
// Hold the class instance.
private static $instance = null;
public function __construct($func = null)
{
if (self::$instance === null) {
self::$instance = $func();
}
return self::$instance;
}
// The singleton decorates the class returned by the closure
public function __call($method, $args)
{
return call_user_func_array([self::$instance, $method], $args);
}
private function __clone(){}
private function __wakeup(){}
};
return $singled;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment