PHP 反射API 例子

学习了《深入PHP 面向对象、模式与实践》,根据自己理解也写了一个类似的反射类使用,以便加深理解

namespace ref\myExample;

abstract class Capacity{

    public function show($skill)
    {
        echo static::class ." show skill:{$skill}";
    }
}

interface  module{

    public function execute();

}

class SupermanModule extends Capacity implements module
{

    public function execute(){

    }
    public function setName($name)
    {
        echo "Superman name:{$name}";
        echo PHP_EOL;
    }

    public function setAge($age)
    {
        echo "Superman age:{$age}";
        echo PHP_EOL;
    }

}

class RouterModule extends Capacity implements module
{


    protected $host;
    protected $username;
    public function execute(){

    }
    public function setHost($host)
    {
        $this->host = $host;

        echo "Router host:{$host}";
        echo PHP_EOL;
    }

    public function setUsername($username)
    {

        echo "Router username:{$username}";
        echo PHP_EOL;
    }

}

class runModule
{

    private $module = [];

    private $configData = [
        "\\ref\\myExample\\SupermanModule"=>[
            ‘name‘=>‘amy‘,
            ‘age‘=>36
        ],

        "\\ref\\myExample\\RouterModule"  => [
            ‘host‘=> ‘rg.com‘,
            ‘username‘=>‘jim‘
        ]
    ];

    public function init(){
        //$interface = new \ReflectionClass(‘\ref\myExample\module‘);
        static $c =0;
        foreach($this->configData as $moduleName=>$param){
            //print_r($param);
//            echo PHP_EOL;
            $moduleClass =new \ReflectionClass($moduleName);
            if(!$moduleClass->isSubclassOf(‘\ref\myExample\module‘)){
//                echo PHP_EOL;
                continue;
            }
            //print_r($moduleClass->getMethods());

            $this->handleMethod($moduleClass,$param);
        }
    }

    public function handleMethod(\ReflectionClass $moduleClass ,$param){
        foreach($moduleClass->getMethods() as $method){
            $args = $method->getParameters();
            print_r($args[0]->getClass());
            print_r($args[0]);
            break;
            //print_r($args);continue;

            if(substr($method->name,0,3)!=‘set‘  ){   //方法名不带有 set
//                echo substr($method->name,0,3);echo PHP_EOL;
                continue;
            }
            $property = strtolower(substr($method->name,3)); //取出如方法名setUsername的左起第三4位开始:Username 并转小写
            if(!isset($param[$property])){//找不到该配置
                //echo $property;echo PHP_EOL;
                continue;
            }
            $module = $moduleClass->newInstance();
            $method->invoke($module,$param[$property]);//调用方法,等同下面一行  $param[‘username‘] = ‘jim‘
            //call_user_func_array([$module,$method->name],[$param[$property]]);
        }


    }
}

$run = new runModule();
$run->init();

  

PHP 反射API 例子

上一篇:最大异或对-Trie--acwing


下一篇:Jenkins REST API 实例