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()类下,但它奇怪,不知何故,我不知道。 –