Skip to content
Advertisement

PHP Interface: Specify ANY visibility

I’m making use of an interface for a set of classes. I have a problem however because I wish for any visibility to be allowed in the interface (That is: public, protected and private).

I need the parent method to only be protected and I need the child method to be private, but I get the error saying

Fatal error: Access type for interface method Baz::qux() must be omitted in <the file with Baz/Bar>.”

I tried specifying other visibility methods in the inteface Baz and removing public, but they all failed.

Is there a way I can do it via the interface? If not, then is there a way I can declare it abstract, I tried that as well, but failed.

interface Baz
{
    public function qux();
}

class Bar implements Baz
{
    protected function qux()
    {
        //do foo
    }
}

class Foo extends Bar implements Baz
{
    private function qux()
    {
        parent::qux();
    }
}

Advertisement

Answer

Methods you declare in Interfaces should be public. You define a contract with an interface. Any non-public methods would be implementation details and those do not belong into an Interface. As the name implies implementation details should go into the concrete classes implementing the interface.

From Wikipedia:

Programming to the interface

The use of interfaces allows a programming style called programming to the interface. The idea behind this is to base programming logic on the interfaces of the objects used rather than on internal implementation details. Programming to the interface reduces dependency on implementation specifics and makes code more reusable.[7] It gives the programmer the ability to later change the behavior of the system by simply swapping the object used with another implementing the same interface.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement