Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

oop

php

interface

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.

like image 323
teepusink Avatar asked Dec 09 '09 20:12

teepusink


People also ask

Can we have private and protected methods in interface?

In general, the protected members can be accessed in the same class or, the class inheriting it. But, we do not inherit an interface we will implement it. Therefore, the members of an interface cannot be protected.

Can an interface contain private methods?

An interface can have private methods since Java 9 version. These methods are visible only inside the class/interface, so it's recommended to use private methods for confidential code. That's the reason behind the addition of private methods in interfaces.

Why interface Cannot have protected methods?

Protected methods are intended for sharing implementation with subclasses. Interfaces have nothing to offer as far as implementation sharing goes, because they have no implementation at all. Therefore all methods on interfaces must be public.

Can we have protected method in interface Java?

The java language specification doesn't currently allow the protected modifier for interface methods.


1 Answers

The PHP manual page about interfaces explicitly states:

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

I guess this explains the error you are getting ;-)

like image 50
Pascal MARTIN Avatar answered Sep 22 '22 06:09

Pascal MARTIN