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();

 


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
© 2014-2018 ITdaan.com 粤ICP备14056181号