开发者

Is it valid to re-declare or override an instance variable through inheritance?

I have an abstract ParentClass with an protected $instanceVariable. Now there's a ChildClass which has also an private $instanceVariable. It sets that to an initial value, like:

private $instanceVariable = 5;

So the child class overrides it and changes the visibility to private. The parent class does not assign a value to that instance variable. It's also declared in the parent class because there are methods that access it.

Is this just fi开发者_运维百科ne with PHP?


You're breaking the Liskov Substitution Principle - I should be able to inherit from the ChildClass secure in the knowledge that my GrandChild class can treat ChildClass as if it was ParentClass. That is that GrandChild should be able to access the protected $instanceVariable.


php will not let you declare such a member, you'll get an error like:

Access level to d::$x must be protected (as in class c) or weaker
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜