2017-06-30 44 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.