1,php中反射API应用的一个实例
- Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--><?php
- class Person
- {
- public $name;
- function __construct($name)
- {
- $this->name = $name;
- }
- }
- interface IModule
- {
- function execute();
- }
- class FtpModule implements IModule
- {
- function execute()
- {
- }
- function setHost($host)
- {
- print "FtpModule::setHost: {$host}\n";
- }
- function setUser($user)
- {
- print "FtpModule::setUser: {$user}\n";
- }
- }
- class PersonModule implements IModule
- {
- function execute()
- {
- }
- function setPerson(Person $person)
- {
- print "PersonModule::setPerson: {$person->name}\n";
- }
- }
- class ModuleRunner
- {
- private $configData = array("PersonModule" => array('person'=>'bob'),
- "FtpModule" => array('host' => 'google.com','user' => 'phinecos')
- );
- private $modules = array();
- function init()
- {
- $interface = new ReflectionClass('IModule');
- foreach( $this->configData as $moduleName => $params) {
- $module_class = new ReflectionClass($moduleName);
- if ( !$module_class -> isSubclassOf($interface) ) {
- throw new Exception("unknown module: $moduleName");
- }
- $module = $module_class->newInstance();
- foreach( $module_class->getMethods() as $method) {
- $this->handleMethod($module, $method, $params);
- }
- array_push($this->modules, $module);
- }
- }
- function handleMethod(IModule $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]);
- } else {
- $method->invoke($module, $arg_class->newInstance($params[$property]));
- }
- }
- }
- $test = new ModuleRunner();
- $test->init();