Q:什么是依赖注入?
答: 有时候代码比理论来得直接,想知道什么是依赖注入,执行下面demo吧
/**
* Describe: 重要的事情多说几遍
* Created by PhpStorm.
* User: querying
* Date: 18-8-27
* Time: 下午5:39
*/
Class ReflectionTest
{
public function index(){
return "数据返回";
}
public function testReflection()
{
$testCon = new Test();
try {
$searchConReflection = new \ReflectionClass(Test::class);
/**
* @var \ReflectionMethod $refMethod
*/
$refMethod = $searchConReflection->getMethod('index');
$refMethodParams = (array) $refMethod->getParameters();
/**
* @var \ReflectionParameter $refMethodParam
*/
$args = [];
foreach ($refMethodParams as $refMethodParam) {
$refClass = $refMethodParam->getClass();
$args[] = $refClass->newInstance();
}
// 调用函数方法,并注入参数
$result = call_user_func([$testCon, 'index'], ...$args);
var_dump($result);
} catch (\Exception $e) {
die($e->getMessage());
}
}
}
(new ReflectionTest())->testReflection();