class ClassArr { public static function ClassStat(){ return [ "a" =>"\\factory\Aa", "b" =>"\\factory\Bb", "c" =>"\\factory\Cc", ]; } /** * @param $type 类库 * @param $classs 工厂库 * @param array $param 参数 * @param bool $needInstance * @return object * @throws ReflectionException * 如果工厂模式方法是静态的那么就直接返回类库 * 不是静态的就通过反射机制返回对象 */ public static function initClass($type,$classs,$param=[],$needInstance=false){ if(!array_key_exists($type,$classs)){ //return false; throw new \Exception("类型{$type}的类库找不到"); } $className= $classs[$type]; return $needInstance==true?(new \ReflectionClass($className))->newInstanceArgs($param):$className; } }
//接口
interface Base { public function code($a,$b); }
//实现 class Aa implements Base { public function code($a, $b) { return $a.$b; } }
//调用 public function factory(){ $class =\factory\ClassArr::ClassStat(); $classObj = \factory\ClassArr::initClass($type='a',$class,[],true); dump($classObj->code(1,2)); }