Is it possible to have an interface that has private / protected methods?

Viewed 57918

Is it possible in PHP 5 to have an interface that has private / protected methods?

Right now I have:

interface iService
{
    private method1();
}

That throws an error:

Parse error: syntax error, unexpected T_STRING, expecting T_VARIABLE

I just want to have confirmation that it is the case that an interface can only contain public methods.

7 Answers

As stated, interfaces can only define the publicly visible methods. I wanted to show an example of how protected methods can be handled. To impose the use of specific protected methods, it is possible to create an abstract class that implements the interface.

This especially makes sense if the abstract class can already handle some of the workload, to simplify the actual implementation. Here for example, an abstract class takes care of instantiating the result object, which is always needed:

First off, the interface.

interface iService
{
   /**
    * The method expects an instance of ServiceResult to be returned.
    * @return ServiceResult
    */
    public function doSomething();
}

The abstract class then defines the internal methods structure:

abstract class AbstractService implements iService
{
    public function doSomething()
    {
        // prepare the result instance, so extending classes
        // do not have to do it manually themselves.
        $result = new ServiceResult();

        $this->process($result);

        return $result;
    }

   /**
    * Force all classes that extend this to implement
    * this method.
    *
    * @param ServiceResult $result
    */
    abstract protected function process($result);
}

The class that does the actual implementation automatically inherits the interface from the abstact class, and only needs to implement the protected method.

class ExampleService extends AbstractService
{
    protected function process($result)
    {
         $result->setSuccess('All done');
    }
}

This way the interface fulfills the public contract, and through the AbstractService class, the internal contract is fulfilled. The application only needs to enforce the use of the AbstractService class wherever applicable.

Big NO, any method in the Interface will never have private or protected access identifier.

**All methods declared in an interface must be public; this is the nature of an interface.

Few other interesting facts about interface

Interfaces can be extended like classes using the extends operator. They can extend only other interfaces. (source: https://www.php.net/manual/en/language.oop5.interfaces.php)

Note that it is possible to declare a constructor in an interface, which can be useful in some contexts, e.g. for use by factories. Signature should be same in the child class.

In your case, even another problem is - function keyword is missing in the function declaration. It should be

interface iService
{
    public function method1();
}
Related