Created
June 23, 2019 11:38
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
# before | |
DB::getInstance()->query('sql'); | |
# after | |
DB::query('sql'); | |
# Notice: All functions in the extended class must be protected. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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