2017-02-12 9 views
0

インターフェイスをコンストラクタパラメータとして
として渡して、そのメソッドを呼び出します。
インターフェイスを__constructor()パラメータとして使用する

ファイル:growth.php

<?php 
    interface Growth { 


     public function growPlants():array; 


     } 

ファイル:test.phpを

<?php 
class DeepForest implements Growth { 

     public function growPlants():array { 
      /* Actions */ 
     } 
    } 

ファイルdeepforest.php:

<?php 
class Forest implements Growth { 

     private $growth; 

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

      public function otherFunction():array { 
      $this->growth->growPlants(); 
     } 

    } 

ファイルforest.php

<?php 
include "deepforest.php"; 
include "forest.php"; 

$deeforest = new DeepForest(); 
$forest = new Forest($deeforest); 

Uncaught Error: Call to undefined method deepForest::otherFunction()

答えて

3

エラーによると、あなたはForestコンストラクタに渡している変数が配列ではなく、Growthのインスタンスです。

さらにコードを投稿したり、渡しているクラスインスタンス、およびそれ自体がGrowthに拡張されているかどうかを確認できますか?

+0

私はそのクラスのオブジェクトを作成しようとしましたが、成功しませんでした。私はそのインターフェイスを実装する別のクラスを作成し、私はそれをフォレスト($ newclassobject)のパラメータとして渡しました。これは、インターフェイスパラメータに基づいてコンストラクタを持つオブジェクトを作成するには、そのインターフェイスでも実装されているオブジェクトを渡す必要があることを意味しますか? –

+0

いいえクラスは、インターフェイスのインスタンスと見なされるために、インターフェイスを実装する必要があります。あなたがあなたが言及した他のクラスの定義を含めるように質問を編集できますか? – fubar

+0

もう一度それを確認してください、私はotherFunction()がDeepForest()クラスの下にある必要があることを理解していますが、どういうわけか不思議です。 –

関連する問題