[英]Why does PHP allow calling private methods from other instances?
PHP would let calls to private methods as long as they come from instances of the same class. 只要它们来自同一个类的实例,PHP就会调用私有方法。
This is how the PHP docs explains it: 这就是PHP文档解释它的方式:
Objects of the same type will have access to each others private and protected members even though they are not the same instances.
即使它们不是相同的实例,相同类型的对象也可以访问彼此私有和受保护的成员。 This is because the implementation specific details are already known when inside those objects.
这是因为在这些对象内部时已经知道实现特定的细节。
Doesn't this break encapsulation? 这不会破坏封装吗? How does the fact that
implementation specific details are known
justify it? implementation specific details are known
的事实如何证明它implementation specific details are known
正确的?
ps Are there other (object oriented) languages that do this? ps还有其他(面向对象的)语言吗?
对于大多数语言都是如此,在java
你也可以这样做,这是因为对象来自同一个实例,它“知道”相同实例具有的所有属性
As an answer to the post scriptum , Delphi (so-called "object pascal") and Lazarus ("free pascal") both allow access to the private properties only in the same unit that the class implementation is coded. 作为post scriptum的答案,Delphi(所谓的“object pascal”)和Lazarus(“free pascal”)都允许仅在与类实现编码相同的单元中访问私有属性。 So you can insert two different classes inside one unit and they have access to each other's private properties.
因此,您可以在一个单元中插入两个不同的类,并且可以访问彼此的私有属性。
It is not allowed if two classes are placed in different units (let's say it's something like a namespace in PHP). 如果两个类放在不同的单元中是不允许的(让我们说它类似于PHP中的命名空间)。
As an answer to "Doesn't this break encapsulation?": 作为“这不打破封装吗?”的答案:
Although the Encapsulation principle in OOP definition is a bit vague. 虽然OOP定义中的封装原则有点模糊。 The way I understand it is it keeps private data and logic in the bounds of a class.
我理解它的方式是它将私有数据和逻辑保存在类的边界内。
Encapsulation is used to hide the values or state of a structured data object inside a class, preventing unauthorized parties direct access to them.
封装用于隐藏类中结构化数据对象的值或状态,防止未授权方直接访问它们。
I don't know if this behaviour of classes in PHP, Java and other languages is good or bad, but I don't think it breaks the Encapsulation of the classes . 我不知道PHP,Java和其他语言中的这种类的行为是好还是坏,但我不认为它破坏了类的封装 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.