Why can you call a private method from outside of the object scope?

人盡茶涼 提交于 2019-12-25 10:23:54

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!