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.
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.
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.
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.
The java language specification doesn't currently allow the protected modifier for interface methods.
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 ;-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With