Php – Best to use Private methods or Protected methods

oopPHP

In a lot of my PHP projects, I end up with classes that have non-public functions that I don't intend to extend.

Is it best to declare these as protected, or private?

I can see arguments both ways – making them private is a far more conservative approach, but it can be argued that they could be made protected later if I want the method to be extended and it makes it clear which methods are extended by base classes.

On the other hand, is using private somehow antisocial, in that it impedes a theoretical future developer from extending my code without modification?

Best Answer

My instinct is to keep them private, until you need them to be otherwise.

It has been argued (sadly I've misplaced the link) that making methods private is antisocial, in much the same way as making them 'final', in that it's fairly dictatorial about how people may use your code.

I'm not convinced, however, and agree that you should expose only what you really need to. The exception would be a library or toolkit, where you'll expect users to want to extend (in the general sense) your code in ways which you would never foresee. In which case making well-chosen methods protected can be seen as providing flex-points.