开发者

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

开发者 https://www.devze.com 2022-12-15 15:32 出处:网络
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:

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

精彩评论

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

关注公众号