2017-06-30 7 views
0

私は自分のクラスの依存性の注入を使用します。依存性注入どのようにクラスのインスタンスが作成されますか?

どのようにPHPがここにオブジェクトのインスタンスを作成しない

class FeedFetcher { 
protected $cache; 
function __construct(Cache $cache) { 
    $this->cache = $cache; 
} 
} 
を:私は new Cache()がない場合

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

を、なぜそれが動作しますか?なぜ私は$cache->method();と呼んでも、キャッシュのインスタンスを作成できないのですか?

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のオブジェクトを渡さない場合:

+0

メソッドが「静的」である場合、メソッドを呼び出すことができます。 http://php.net/manual/en/language.oop5.static.php –

+0

なぜか: '__construct(Cache new $ cache)'を参照してください。 – ITMANAGER

+0

依存性注入がこのように動作しないため、原因(新しい$ cache)は、クラスを拡張するか、または特性を使用するのに最適です。 –

答えて

0

Cache $cacheFeedFetcherのオブジェクトを作成するときにCacheのインスタンスを渡す必要があることを述べ、Type declarationまたはタイプのヒントですエラー:

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

関連する問題