Skip to content

Instantly share code, notes, and snippets.

@bragle
Created June 23, 2019 11:38
Show Gist options
  • Save bragle/7393055722a87baad40110ad19f87fdd to your computer and use it in GitHub Desktop.
Save bragle/7393055722a87baad40110ad19f87fdd to your computer and use it in GitHub Desktop.
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.
<?php
# before
DB::getInstance()->query('sql');
# after
DB::query('sql');
# Notice: All functions in the extended class must be protected.
<?php
class singletonConstructor {
private function __construct(){}
private static $children = [];
private static function init($class){
if(!isset(self::$children[$class])){
self::$children[$class] = new $class;
}
}
private static function call($name, $args){
$class = get_called_class();
self::init($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