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()
私はそのクラスのオブジェクトを作成しようとしましたが、成功しませんでした。私はそのインターフェイスを実装する別のクラスを作成し、私はそれをフォレスト($ newclassobject)のパラメータとして渡しました。これは、インターフェイスパラメータに基づいてコンストラクタを持つオブジェクトを作成するには、そのインターフェイスでも実装されているオブジェクトを渡す必要があることを意味しますか? –
いいえクラスは、インターフェイスのインスタンスと見なされるために、インターフェイスを実装する必要があります。あなたがあなたが言及した他のクラスの定義を含めるように質問を編集できますか? – fubar
もう一度それを確認してください、私はotherFunction()がDeepForest()クラスの下にある必要があることを理解していますが、どういうわけか不思議です。 –