John Roca John Roca - 3 months ago 18
PHP Question

How to impose contract to subclass from parent class implementation

If I have an interface and I want the functions in my interface to be implemented in my sub class but the parent class must implement the interface. And Sub class extends Parent Class.

Here is what I want.

interface MyInterface {
public function find();
}


class B implements MyInterface {
}

class A extends B {
}


But an error is thrown saying find() function must be added in class B.

Anyone who could enlighten me on what am I doing wrong? thanks!

Answer

Interface is a structure, which contains a set of fields and methods that have to be implemented in every class that implements this interface. If your B class implements MyInterface it means it has to implement all of its methods/fields.

interface MyInterface
{
     public function find();
}

class B implements MyInterface {
    public function find()
    {
       echo "Hello world";
    }
}

Does A class have to implement this method too? I'll leave it as your homework.