动态注入 A、B类为Demo类的$a、$b属性
<?php trait InjectProperty { public function __get($name) { $class = new \ReflectionClass($this); $comment = $class->getDocComment(); $hasMatched = preg_match_all('/(@property.*?)(?:\r\n|\r|\n)/i', $comment, $matches); if ($hasMatched) { foreach ($matches[1] as $property) { list(, $className, $objName) = preg_split('/\s+/', $property); if ($objName == '$' . $name) { return new $className(); } } } } }
namespace App\Controller;
/** * @property \Utils\A $a * @property \Utils\B $b */ class Demo { use InjectProperty; } namespace Utils; class A { public $name = 'a'; public function say() { return 'my name is ' . $this->name; } } class B { public $name = 'b'; public function say() { return 'my name is ' . $this->name; } } // use echo '<pre>'; var_dump((new \App\Controller\Demo)->a);