PHP 反射API

在框架中,反射用的比较多,是一种比较灵活的统一实例化类,规范化接口,用起来很方便,废话不多说,直接上代码,例子看懂基本就会用php的反射了,主要部分已添加注释;不明白的可以留言给我。

interface module{
    function execute();
}
class ftpModule implements module{
    function setHost($host){
        print "ftpModule::setHost():$host
";
    }
    function setUser($user){
        print "ftpModule::setUser():$user
";
    }
    function execute()
    {
        
    }
}

class moduleRun{
    private $configData=array(
        'ftpModule'=>array('host'=>'www.ceshi.com','user'=>'bob'),
    );
    private $modules = array();//缓存对象

    function init(){
        $interface = new ReflectionClass('Module');
        foreach($this->configData as $modulename=>$params){
            $module_class = new ReflectionClass($modulename);
            if( ! $module_class->isSubclassOf($interface)){
                throw new Exception("unknow module type");
            }
            $module = $module_class->newInstance();//创建module示例
            foreach ($module_class->getMethods() as $method){
                $this->handleMethod($module,$method,$params);
            }
            array_push($this->modules,$module);//缓存对象
        }
        return $this->modules;
    }

    function handleMethod(Module $module,ReflectionMethod $method,$params){
        $name =$method->getName();
        $args = $method->getParameters();
        if(count($args) != 1 || substr($name,0,3) != 'set'){
            return false;
        }
        $property = strtolower(substr($name,3));

        if(! isset($params[$property])){
            return false;
        }
        $arg_class =$args[0]->getClass();
        if(empty($arg_class)){
            $method->invoke($module,$params[$property]);//调用set方法
        }else{
            $method->invoke($module,$arg_class->newInstance($params[$property]));
        }

    }


}

$moduleRun = new moduleRun();
$moduleRun->init();
原文地址:https://www.cnblogs.com/happy-dream/p/6610145.html