Skip to content

Instantly share code, notes, and snippets.

Created June 23, 2019 11:38
What would you like to do?
A singleton class loader. Will convert static calls to nonstatic calls and construct the class only when needed. Use this with caution, as it may make your code less readable.
# before
# after
# Notice: All functions in the extended class must be protected.
class singletonConstructor {
private function __construct(){}
private static $children = [];
private static function init($class){
self::$children[$class] = new $class;
private static function call($name, $args){
$class = get_called_class();
if(!method_exists($class, $name)){
throw new Error('Method ' . $name . ' does not exist in ' . $class);
return (self::$children[$class])->$name(...$args);
public function __call($name, $args){
return self::call($name, $args);
public static function __callStatic($name, $args){
return self::call($name, $args);
public static function _exists($class){
return isset(self::$children[$class]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment