问题
I am curious as to why this is allowed to work, whereby you can call and successfully execute a private method on an object from outside of the object scope providing you are making the call from a class of the same type.
The private method call from a public scope to me seems not to satisfy the criteria of a private method, so why is this allowed in both PHP and Java?
<?php
class A
{
public function publicMethod ()
{
$obj = new static;
$obj->privateMethod ();
}
private function privateMethod ()
{
echo 'why does this execute?';
}
}
$obj = new A;
$obj->publicMethod ();
回答1:
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.
-- Visiblity, PHP Manual
回答2:
Private modifier Defines that you call the property or method in the local scope By that i mean the same class. Although it's own class is the only caller, you can use it in a public method and then call that public method outside the local scope ( the owner class )
来源:https://stackoverflow.com/questions/27066518/why-can-you-call-a-private-method-from-outside-of-the-object-scope