//容器类 class Container { /** * 存放容器的数据 * @var array */ public $instances = []; public static $instance; private function __construct() { } /** * 单例模式 * @return mixed */ public static function getInstance(){ if(is_null(static::$instance)){ static::$instance = new static; } return static::$instance; } public function set($key,$value){ $this->instances[$key] = $value; } /** * 获取容器里面的实例用到反射机制 * @param $key * @return mixed */ public function get($key,$arg=''){ if(!empty($this->instances[$key])){ $key = $this->instances[$key]; } $reflect = new \ReflectionClass($key); //获取类的构造函数 $c = $reflect->getConstructor(); if(!$c){ return new $key; } //获取类的参数 $params = $c->getParameters(); if(empty($params)){ return new $key; } foreach ($params as $param) { $class =$param->getClass(); if(!$class){ $args[] = $arg; }else{ //dump($class->name); $args[] = $this->get($class->name); } } return $reflect->newInstanceArgs($args); } }
class Person { //Car 注入 person public function __construct(Car $obj,$a=11){ $this->obj = $obj; $this->a = $a; } /** * @return mixed */ public function buy(){ return $this->a ."|".$this->obj->pay(); } }
class Car { public function pay(){ return 1234; } }
//设置类挂载 \di\Container::getInstance()->set("person","\di\Person"); \di\Container::getInstance()->set("car","\di\Car"); $obj = \di\Container::getInstance()->get("person",$a=1); //dump($obj);die; dump($obj->buy());