PHP 通过构造器进行依赖注入 demo

class A{
public $b;
public $f; function __construct( B $b , $f = 1 ){
$this->b = $b;
$this->f = $f;
}
} class B{}
class GenClass{ public function getObj( $class ,$params = [] ){
$rel = new ReflectionClass( $class );
$paramObjs = $rel->getConstructor()->getParameters();
$parIns = $this->getParIns($paramObjs);
$ret = $rel->newInstanceArgs($parIns);
return $ret;
} public function getParIns( $paramObjs ){
$ret = [];
foreach ( $paramObjs as $params){
$dep = $params->getClass();
if ($params->isDefaultValueAvailable()) {
$ret[] = $params->getDefaultValue();
}else{
$ret[] = $this->getIns( $params->name );
}
}
return $ret;
} public function getIns( $class, $param = [] ){
return new $class();
}
} $s = (new GenClass())->getObj('A',[]);
var_dump($s);
die();
上一篇:转 Eric Raymond对于几大开发语言的评价


下一篇:Shell 字符串处理