直接用代码来说明
namespace Database; use ReflectionMethod; class connection { public function __construct (){ } //通过构造方法进行依赖注入MySQL_Adapter public function connect (MySQL_Adapter $MySQL_Adapter) { echo "connection:"; echo "\n"; $MySQL_Adapter->connect(); } } class MySQL_Adapter { public function __construct ($instance_parameters){ echo 'MySQL_Adapter instance,parameters:'.$instance_parameters; echo "\n"; } public function connect (){ echo "MySQL_Adapter connect"; echo "\n"; } } class app { public static function run ($instance, $method) { // 利用发射机制获取实例$instance方法method的内部信息 $reflector = new ReflectionMethod($instance, $method); $parameters = array(); // 遍历方法$method的参数 foreach ($reflector->getParameters() as $key => $parameter) { $class = $parameter->getClass(); //如果参数是类的话 if ($class) { //获取类名 $reflector_classname = $class->name; //进行实例化 $classname_instance = new $reflector_classname('reflector'); //保存实例 $parameters[$key] = $classname_instance; } } //执行$instance实例的方法$method,并且把参数$parameters传给方法 //$parameters包括已经被实例化的对象参数MySQL_Adapter call_user_func_array([$instance,$method],$parameters); } } $connection = new connection(); app::run($connection, 'connect');
Leave a Reply