类注释注入其他对象为属性
动态注入 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);
分情破爱始乱弃,流落天涯思别离。
如花似玉负情意,影如白昼暗自迷。
随风浮沉千叶落,行色匆匆鬓已稀。