<?php
/**
* Class A
*/
class A
{
protected B $b;
/**
* A constructor.
* @param B $b
*/
public function __construct(B $b)
{
$this->b = $b;
}
public function aMethod(): void
{
echo "我是A的方法" . $this->b->say();
}
}
class B
{
protected C $c;
protected D $d;
/**
* B constructor.
* @param C $c
* @param D $d
*/
public function __construct(C $c, D $d)
{
$this->c = $c;
$this->d = $d;
}
/**
* @return string|null
*/
public function say(): ?string
{
return $this->c->say() . PHP_EOL . $this->d->say();
}
}
class C
{
public function say(): string
{
return '我是C';
}
}
class D
{
public function say(): string
{
return '我是D';
}
}
class Ioc
{
protected $instance;
/**
* @param $class
* @return mixed|object
* @throws ReflectionException
*/
protected function getInstance($class)
{
$reflector = new ReflectionClass($class);
// 获取类的注释信息
// echo $reflector->getDocComment();
// 获取反射类的构造函数信息
$constructor = $reflector->getConstructor();
if (!is_null($constructor)) {
$dependencies = $constructor->getParameters();// 获取构造方法所需要的参数
// 如果构造方法没有依赖其他对象直接返回对象实例
if (!$dependencies) {
return new $class();
}
foreach ($dependencies as $dependency) {
if (!is_null($dependency->getClass())) {
$args[] = $this->make($dependency->getClass()->name);
}
}
return $reflector->newInstanceArgs($args);// 从给定参数创建新的类实例。
}
// 没有构造方法直接返回实例
return new $class();
}
/**
* @param $class
* @return mixed|object
* @throws ReflectionException
*/
public function make($class)
{
return $this->getInstance($class);
}
}
$ioc = new Ioc();
$obj = $ioc->make('A');
echo $obj->aMethod();
PHP依赖注入
最新推荐文章于 2023-07-28 08:45:00 发布