简体   繁体   English

子类将继承的方法设为私有

[英]Child class making inherited methods private

So, basically, I have class B and C , whose parent is class A . 因此,基本上,我有B级和C ,其父class Aclass 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.

相关问题 PHP:为什么子类的继承方法访问父级的私有属性? - PHP: Why do Inherited Methods of Child Class access Parent's Private Properties? 继承的函数无法访问子类的私有变量 - Inherited function doesn't access private var of the child class 如何在 PHP 中的子 class 继承方法中定义更严格的类型? - How to define stricter typing in child class inherited methods in PHP? 如何通过在父类中调用get_class_methods来获取子进程的私有方法 - how to get private methods of a child by calling get_class_methods within the parent class 从继承的类调用私有方法 - Call private method from inherited class 受保护的变量是否在继承的 class 中变为私有? - Does a protected variable become private in an inherited class? 通过继承的静态方法创建继承的类的新实例 - Creating a new instance of an inherited class through the inherited static methods PHP构造函数:“继承的”构造函数是否使用Inherited或Parent类的重写方法? - PHP Constructors: Will an “inherited” constructor use Inherited or Parent class overriden methods? 如何获取非继承的PHP类方法? - How to get non inherited PHP class methods? 获取在类中声明的所有公共方法,而不是继承 - Get all public methods declared in the class, not inherited
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM