【问题标题】:Accessing a protected method from a parent class从父类访问受保护的方法
【发布时间】:2013-04-06 06:21:09
【问题描述】:

我知道,当我希望一个方法仅对扩展当前类以及当前类的所有类可用时,我应该将它设置为“受保护”。

好的,grandChildClass::method2() 应该受到保护,因为孙子是从孩子扩展而来的。

但是如果从父类如 parentClass::method2() 访问应该是什么?

class parentClass
{
    public function method1() {$this->method2();}
}

class childClass extends parentClass
{
    protected function method2() {}
}

class grandChildClass extends childClass 
{
    public function method3() {$this->method2();}
}

【问题讨论】:

标签: php oop class


【解决方案1】:

如果你尝试

$p = new parentClass;
$p->method1();

未定义的方法会出现致命错误。

致命错误:调用未定义的方法parentClass::method2() in ...在线...

但是,这会正常工作:

$c = new childClass;
$c->method1();

$g = new grandChildClass;
$g->method1();
$g->method3();

所有这些都将调用method2,如childClass 所定义的那样。

【讨论】:

  • 为了更简洁,parentClass 可以定义一个纯虚拟版本的method2,如下virtual method2() = 0;。这将明确要求任何 childClass 实现 method2() 函数,以便可以调用我的 parentClass 方法。
  • 谢谢,我希望它能像你说的那样工作!我把自己弄糊涂了,并且正在访问在我的 parentClass 中定义的方法,但是从 grandchildClass 中,所以显然 childClass 方法工作得很好。
  • @Alan:PHP 中没有 virtual 方法。您可以将一个类及其方法定义为abstract(这意味着它们只有定义,不能实例化)。
  • 谢谢@MadaraUchiha,这就是我的意思,将其定义为抽象的。我把我的 C++ 和 PHP 搞混了。
  • 另一种方式来做这样的事情 :: stackoverflow.com/questions/17174139/…
猜你喜欢
  • 2020-05-02
  • 2014-05-01
  • 2020-07-26
  • 1970-01-01
  • 2012-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多