动态注入 A、B类为Demo类的$a、$b属性
<?php trait InjectProperty { public function __get($name) { $class = new ReflectionClass($this); $comment = $class->getDocComment(); $hasMatched = preg_match_all('/(@property.*?)(?: | | )/i', $comment, $matches); if ($hasMatched) { foreach ($matches[1] as $property) { list(, $className, $objName) = preg_split('/s+/', $property); if ($objName == '$' . $name) { return new $className(); } } } } }
namespace AppController;
/** * @property UtilsA $a * @property UtilsB $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 AppControllerDemo)->a);