0
我想通過一個接口作爲構造函數參數
到實現它並調用其方法的類。
使用接口作爲__constructor()參數
文件:growth.php
<?php
interface Growth {
public function growPlants():array;
}
文件:forest.php
<?php
class Forest implements Growth {
private $growth;
public function __construct(Growth $growth) {
$this->growth = $growth;
}
public function otherFunction():array {
$this->growth->growPlants();
}
}
文件:deepforest.php
<?php
class DeepForest implements Growth {
public function growPlants():array {
/* Actions */
}
}
文件:test.php的
<?php
include "deepforest.php";
include "forest.php";
$deeforest = new DeepForest();
$forest = new Forest($deeforest);
Uncaught Error: Call to undefined method deepForest::otherFunction()
我只是試圖創建該類的對象,但沒有成功。比我創建另一個類實現該接口,並將其作爲參數傳遞給Forest($ newclassobject)。這是否意味着爲了創建一個基於接口參數的構造函數的對象,我需要傳遞一個由該接口實現的對象? –
不需要。一個類需要實現接口,以便它被視爲接口的一個實例。你能編輯你的問題來包含你提到的其他類的定義嗎? – fubar
請再檢查一次,我明白其他函數()需要在DeepForest()類下,但它奇怪,不知何故,我不知道。 –