Reputation: 5784
I have a functionality that need to be shared by a few classes that manage a common aspect of my software. In Java, i would have all theses classes in the same package and the common functionality would be in a protected method in a helper class.
In PHP, protected method mean that you can only use it in sub-classes so my current solution is to make the method protected and have all the classes needing this method to extend the helper class. The problem with my current solution is the fact than you can't inherit multiple classes so lets say i need to helper classes, im ...
So, is there a way to have a method visibility comparable to java protected in PHP? If not, any cleaner way to solve my problem?
Upvotes: 1
Views: 391
Reputation: 5675
You could try namespaces (5.3) and reference the utility class instead of extending it. This doesn't quite solve the problem but it does help isolate your class. I try to avoid using private methods.
In PHP 5.4 they added traits which kind of allow a class to extend multiple classes. Schleis has already answered with that.
Upvotes: 2
Reputation: 43710
It sounds that you are looking to use traits.
http://php.net/manual/en/language.oop5.traits.php
This would let you define your shared protected method and provide to the classes that require it. I would recommend implementing this with an interface so that you can specify that the method provided by the trait has to be there.
PHP only lets you extend one abstract class however you can implement multiple interfaces.
Upvotes: 7