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(); } }
You can never have a private method in an interface. Any methods in an interface are assumed to be in use and should not be changed. Interfaces is the PHP link, but this is standard in OO programming.
PHP has three visibility keywords - public, private and protected. A class member declared with public keyword is accessible from anywhare. A protected member is accessible from within its class and by inheriting class.
No. We cannot override an interface method if it's visibility is not public. And if it has its visibility as public then you can override it with the same method signature (i.e., with the same access specifier public) whenever you implement the interface to any class.
Yes, more than two interfaces can be implemented by a single class. From the PHP manual: Classes may implement more than one interface if desired by separating each interface with a comma.
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.
A interface is a contract between 2 parties, a agreement how they communicate.
It makes no sense to make methods protected or private, because the other party will not see those.
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