从祖父母继承的 PHP



我试图从"受保护的静态函数"的角度理解PHP继承是如何工作的。

假设我们有 3 个类(A、B、C),其中 C 继承自 B,B 继承自 A:

class A{
# ... properties & methods
# then we have targetFunc()
protected static function grandparentFn(){
// some action
}
}
class B extends A{
protected static function parentFn(){
// some action
}
}
class C extends B{
}

当我这样做时:

C::parentFn() // it fails .... (expected, due to protected)

然后当我这样做时:

C::grandparentFn() // it works .... ????

grandparentFn()不是受到保护吗?为什么如上所述可以访问它?即使对于静态方法,可见性如何在这里应用?

它不起作用。声明为受保护的成员只能在类本身内访问,并且只能通过继承类和父类进行访问。这也适用于静态保护方法。

因此,当您想访问静态保护方法时,您只能从类、父类或子类内部进行操作。

https://www.php.net/manual/en/language.oop5.visibility.php

它不起作用:Call to protected method A::grandparentFn() from context '' in [...][...]:18

可以在此处找到示例:http://sandbox.onlinephpfunctions.com/code/dc1750647f242840ef9a3606692ddaef8e906648

最新更新