Why can you call a private method from outside of

2019-09-07 13:44发布

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 ();

2条回答
Emotional °昔
2楼-- · 2019-09-07 14:16

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

查看更多
混吃等死
3楼-- · 2019-09-07 14:21

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 )

查看更多
登录 后发表回答