2017-02-12 51 views
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()

回答

3

根据错误,你传递给Forest构造函数的变量是一个数组,而不是Growth一个实例。

你可以发布更多的代码,或确认你通过什么类实例,以及它本身是否延伸Growth

+0

我只是试图创建该类的对象,但没有成功。比我创建另一个类实现该接口,并将其作为参数传递给Forest($ newclassobject)。这是否意味着为了创建一个基于接口参数的构造函数的对象,我需要传递一个由该接口实现的对象? –

+0

不需要。一个类需要实现接口,以便它被视为接口的一个实例。你能编辑你的问题来包含你提到的其他类的定义吗? – fubar

+0

请再检查一次,我明白其他函数()需要在DeepForest()类下,但它奇怪,不知何故,我不知道。 –