0

I am trying to pass an Interface as a constructor parameter
into a class that implements it and calls its method .

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);

Uncaught Error: Call to undefined method deepForest::otherFunction()

0

1 Answer 1

3

According to the error, the variable you're passing to the Forest constructor is an array, and not an instance of Growth.

Can you post more code, or confirm what class instance you're passing in and whether it itself extends Growth?

Sign up to request clarification or add additional context in comments.

6 Comments

i was just trying to create an object of that class but no success. Than i created another class that implements that interface and i passed it as a parameter over the Forest ($newclassobject). Does this mean that in order to create an object that has a constructor based on a interface parameter, i need to pass an object that is implemented by that interface too ?
No. A class needs to implement the interface for it to be considered an instance of the interface. Can you edit your question to include the definition of the other class you mentioned?
Please check it again , i understand that the otherFunction() needs to be under DeepForest() class but it is strange somehow, i dont know.
Well your original error has been resolved. Where are you calling otherFunction() on the DeepForest instance to get that error? There's nothing in the code you've posted that will cause that error.
I think you wants to create a DeepForest class which is inherited from Forest class. The Forest consists of plants which are objects of class Plant, and you can grow all the plants in DeepForest together, so you create a method called growPlants(), which take you to set the Forest class implementing GrowthInterface. If so, I have the brief code example for you.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.