<?php
class A
{
protected 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;
public function __construct(C $c, D $d)
{
$this->c = $c;
$this->d = $d;
}
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;
protected function getInstance($class)
{
$reflector = new ReflectionClass($class);
$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();
}
public function make($class)
{
return $this->getInstance($class);
}
}
$ioc = new Ioc();
$obj = $ioc->make('A');
echo $obj->aMethod();