類型約束

class One
{
    private $closure;

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

    public function doSomething()
    {
        if (...) {
            // 用的時候再實例化
            // 實現懶加載
            $instance = $this->closure();
            $instance->do(...)
        }
        ...
    }
}
...

$instance = new One(function () {
    // 類One外部依賴了類Two
    return new Two();
});
$instance->doSomething();
...
相關文章
相關標籤/搜索