类注释注入其他对象为属性

动态注入 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);

 

posted @ 2019-07-17 14:02  白開水  阅读(240)  评论(0编辑  收藏  举报