Emanuil Rusev
Emanuil Rusev

Reputation: 35275

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.

This is how the PHP docs explains it:

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?

p.s. Are there other (object oriented) languages that do this?

Upvotes: 5

Views: 293

Answers (3)

Harry Dobrev
Harry Dobrev

Reputation: 7706

As an answer to "Doesn't this break encapsulation?":

Although the Encapsulation principle in OOP definition is a bit vague. 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.

Upvotes: 1

Voitcus
Voitcus

Reputation: 4456

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. 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).

Upvotes: 1

Dima
Dima

Reputation: 8662

This is true for most languages, in java you can do it too, this is because the object is from the same instance, it "knows" all the properties same instances have

Upvotes: 1

Related Questions