[英]Child class making inherited methods private
So, basically, I have class B
and C
, whose parent is class A
. 因此,基本上,我有B
级和C
,其父class A
是class A
。
Class A
has public method set()
. Class A
具有公共方法set()
。 But I want method set()
to be private in class B
and public in class C
, so you can call it from instances of class C
and you can't call it from instances of class B
. 但是我希望方法set()
在B
类中是私有的,而在C
类中是公共的,因此您可以从C
类的实例调用它,而不能从B
类的实例调用它。
Is it possible in PHP? PHP中可能吗?
No. The theory is that you should be able to use instances of a sub-class anywhere you could use instances of the parent, without knowing which you have. 不。理论是,您应该可以在可以使用父级实例的任何地方使用子类的实例,而无需知道自己拥有哪个。
If class A has a public method foo
, I should be able to call $a->foo()
for any value where $a instanceof A
is true. 如果类A具有公共方法foo
,则我应该能够为$a->foo()
$a instanceof A
为true的任何值调用$a->foo()
。
If the sub-class B makes this method private, I can't make the call. 如果子类B将此方法设为私有,则无法进行调用。
The fancy name for this is the Liskov Substitution Principle. 这个名字叫Liskov Substitution Principle。
You are, however, free to make the method behave how you like, so could for instance throw an Exception in class B - but make sure to always catch it somewhere. 但是,您可以随意使该方法表现出自己喜欢的方式,例如可以在类B中引发Exception-但请确保始终将其捕获在某个地方。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.