使用Interface作为__constructor()参数

时间:2017-02-12 22:01:20

标签: php class constructor interface implementation

我试图将Interface作为构造函数参数传递 进入实现它并调用其方法的类。

file:growth.php

<?php  
   interface Growth {


        public function growPlants():array;


        }

file:forest.php

<?php 
class Forest  implements Growth {

        private $growth;

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

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

    }

file:deepforest.php

<?php 
class DeepForest implements Growth {

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

file:test.php

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

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

未捕获错误:调用未定义的方法deepForest :: otherFunction()

1 个答案:

答案 0 :(得分:3)

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

您可以发布更多代码,或确认您传入的类实例以及它本身是否延伸Growth