Matt Gibson
Matt Gibson

Reputation: 14949

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

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

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

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?

Upvotes: 14

Views: 9742

Answers (4)

KingCrunch
KingCrunch

Reputation: 131841

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.

Upvotes: 17

jotadeaa
jotadeaa

Reputation: 1

If you think expossing a private/protected method in a subclass represents a problem, just make the method final.

See it this way: by NOT making a method final, you are allowing any subclass to overriding it at will; this obviously includes increasing its visibility.

Upvotes: 0

GordonM
GordonM

Reputation: 31730

If a superclass exposes a method publicly, then all its subclasses must also expose the same method (or an overridden version), therefore reducing the accessibility of a method is a subclass is illegal in PHP (and pretty much every class-based OO language).

The opposite is not true, so increasing the accessibility of methods in subclasses is perfectly fine.

Upvotes: 0

fivedigit
fivedigit

Reputation: 18672

You can't decrease the visibility of class members, only increase them.

Imagine a class A which has a public method, and a subclass B would make it private. B could be treated as a type A, for which it is assumed that it has that public method.

Upvotes: 11

Related Questions