Php – Why does PHP allow protected and private methods to be made public via an override in subclasses

encapsulationinheritanceoopPHPvisibility

From some brief fiddling about, I find I get an error when overriding superclass methods in a subclass when I do the following:

  • Override a protected superclass method with a private subclass method
  • Override a public superclass method with a protected or private subclass method

However, If I do it in the other direction, no error is thrown:

  • Overriding a private superclass method with a protected or public subclass method
  • Overriding a protected superclass method with a public subclass method

This seems counter intuitive to me – I was expecting it to work the other way around in order to enforce information hiding and encapsulation. This appears to allow poor design by allowing internals to be exposed in a way that may break other methods and I can't see a case when this would be a good idea. Why has it been implemented this way and what have I missed?

Also, is this standard practice in other programming languages?

Best Answer

What you call "enforce information hiding" is something, that may break subclasses, because suddenly properties and methods may disappear. You cannot break things by loosing restrictions this way.

With private is a bit different: In this case the property/method does not exists from the child class' point of view. Thus there is no reason, why a subclass may not introduce a property with that name, because it will be a different property.

You are right, that this may lead to poor design, but you can always build an application with poor design.