2017-06-30 46 views
0

我用自己的類依賴注射:依賴注入如何創建類的實例?

class FeedFetcher { 
protected $cache; 
function __construct(Cache $cache) { 
    $this->cache = $cache; 
} 
} 

如何PHP創建實例對象的位置:

function __construct(Cache $cache) { $cache->method(); } 

,如果我沒有new Cache()爲什麼它的工作?爲什麼我可以通過創建Cache的實例來調用$cache->method();

+0

如果他們的方法是「靜態」,則可以調用方法。見http://php.net/manual/en/language.oop5.static.php –

+0

爲什麼不是:'__construct(Cache new $ cache)'? – ITMANAGER

+0

因爲依賴注入不是這樣工作的,所以原因(new $ cache)最好是實踐擴展類或使用特性。 –

回答

0

Cache $cacheType declaration或暗示類型,指出創建的FeedFetcher對象時,你必須通過Cache一個實例:

class FeedFetcher { 
    protected $cache; 

    function __construct(Cache $cache) { $cache->method(); } 
} 

// create a Cache object 
$c = new Cache; 
// pass Cache object to constructor of FeedFetcher 
$f = new FeedFetcher($c); 

如果不通過Cache類型的對象就會產生一個錯誤:

Fatal error: Uncaught TypeError: Argument 1 passed to FeedFetcher() must be an instance of Cache, none/null/something else given.