为什么要从对象范围之外调用私有方法? [英] Why can you call a private method from outside of the object scope?

查看:102
本文介绍了为什么要从对象范围之外调用私有方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇为什么允许这样做,如果您要从相同类型的类进行调用,则可以从对象范围之外的对象上调用并成功执行私有方法.

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.

从公共范围到我的私有方法调用似乎不满足私有方法的标准,那么为什么PHP和Java都允许这样做?

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

推荐答案

相同类型的对象将可以彼此访问私有成员和受保护成员,即使它们不是同一实例.这是因为在这些对象中时,已经知道实现的特定细节.

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.

-可见性,PHP手册

这篇关于为什么要从对象范围之外调用私有方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆