【问题标题】:Use Interface as __constructor() parameter使用接口作为 __constructor() 参数
【发布时间】:2017-06-30 19:58:57
【问题描述】:

我正在尝试将接口作为构造函数参数传递
进入一个实现它并调用它的方法的类。

文件: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);

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

【问题讨论】:

    标签: php class constructor interface implementation


    【解决方案1】:

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

    您能否发布更多代码,或确认您传入的是哪个类实例以及它本身是否扩展了Growth?

    【讨论】:

    • 我只是试图创建该类的对象,但没有成功。然后我创建了另一个实现该接口的类,并将它作为参数传递给 Forest ($newclassobject)。这是否意味着为了创建一个具有基于接口参数的构造函数的对象,我也需要传递一个由该接口实现的对象?
    • 没有。一个类需要实现接口才能被视为接口的实例。您可以编辑您的问题以包含您提到的其他类的定义吗?
    • 请再检查一次,我知道 otherFunction() 需要在 DeepForest() 类下,但不知何故很奇怪,我不知道。
    • 你原来的错误已经解决了。您在DeepForest 实例上调用otherFunction() 以获取该错误?您发布的代码中没有任何内容会导致该错误。
    • 我想你想创建一个继承自 Forest 类的 DeepForest 类。 Forest由Plant类对象的植物组成,你可以一起种植DeepForest中的所有植物,所以你创建一个名为growPlants()的方法,它带你设置实现GrowthInterface的Forest类。如果是这样,我有一个简短的代码示例给你。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-19
    • 1970-01-01
    • 1970-01-01
    • 2012-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多