我刚刚编写了以下代码(预计它会失败),但我真的不明白为什么会这样:
<?php
abstract class Test1 {
protected function methodTest1() {}
}
class Test2 extends Test1{
public function methodTest2() {
$test3 = new Test3();
$test3->methodTest1();
}
}
class Test3 extends Test1 {
}
$test2 = new Test2();
$test2->methodTest2();
预期结果: fatal error ,因为我正在调用一个类的“ protected ”成员,就像它是一个公共(public)成员一样
实际结果:...有效
我错过了什么吗?
我假设它与 Test2 扩展 Test1 的事实有关,因此它可以访问它,但在这种情况下它没有意义,因为我不是从 Test2 而是从 Test3 上下文调用“test1()” .所以这意味着“Test3”是一个全新的实例,基本上不公开任何方法。在我看来,这段代码适用于 2 个对象的 2 个完全不同的实例
连 IDE (PHPStorm) 都说没问题。
有什么线索吗?
最佳答案
这是正确的行为。可见性与类有关,它不限于对象(类实例)。所以这是有道理的:
class Foo {
private $field;
public function method(Foo $fooInstance) {
//have access to everything from $fooInstance
//cause I'm already in that class
$fooInstance->field;
}
}
对于 protected 成员,如果您正在使用并且在任何子类等中,您将有权访问。
关于PHP 从子上下文中以公共(public)方式调用 protected 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27608467/