2018年7月25日 星期三

php 讓 container 注入模組的方式

class Container {

    public $name = 'a';
    public $age = 19;
    public $load;

    public function __construct() {
        $this->load = new Loader($this);
    }

    public function getName() {
        printf('<p>%s</p>', $this->name);
    }

}

// 注入模組
class Loader {
    public $container;

    public function __construct($container) {
        $this->container = $container;
    }

    public function __get($name) {

        if (isset($this->container->$name)) {
            return $this->container->$name;
        }

    }

}

$a = new Container();

$load = $a->load;
var_dump($load->name);

2018年7月20日 星期五

php 取得最上層的 className

function getParentClassName($o) {
    $res = $o;

    while (TRUE) {

        $ref = new ReflectionClass($res);
        $r = $ref->getParentClass();

        if ($r) {
            $ref = $r;
        } else {
            break;
        }
        // className
        $res = $ref->getName();
    }

    return $res;
}