【问题标题】:Inheriting Child Methods继承子方法
【发布时间】:2014-01-15 13:59:55
【问题描述】:

好的,我想知道 PHP 中的父类是否可以从子类或“扩展”类访问或“继承”方法。例如,如果我的父类有一个名为foo 的方法,而子类有一个名为bar 的方法,我可以从foo 调用bar 吗?

问题 2:假设我有一个名为“actions”的父类,它有一个名为“perform”的方法,它将参数“foo”作为字符串。然后我们有两个单独的类,分别称为“actionA”和“actionB”。每个子类都包含一个名为“method-”className“”的方法,如果可能的话,我将如何根据提供给“actions”类中“perform”方法的参数来调用子方法?

【问题讨论】:

  • 您可以使用static::bar()foo() 调用bar()late static binding 但这不是父级从子级继承的情况,而是具有两种方法的实例化子级

标签: php inheritance


【解决方案1】:

是和不是。

不,因为那样父类不能自己工作。

是的,因为 PHP 为此提供了一个构造:抽象类。抽象类本身不能实例化,但其他类可以从它继承。抽象类中的抽象方法不必有主体,并且必须由任何非抽象子类(如接口)实现。

好吧,让代码说话:

<?php

// note the "abstract" keyword
abstract class ParentClass {

    public function foo() {
        $this->bar();
    }

    // again, note the "abstract" keyword and note how the method does
    // not have a body (i.e. not any actual code)
    abstract public function bar();
}

class ChildClass extends ParentClass {

    public function bar() {
        echo 'bar called!';
    }

}

$foo = new ParentClass(); // this will raise an error
$bar = new ChildClass(); // this will work
$bar->foo(); // this will echo "bar called!"
$bar->bar(); // ... as will this

?>

【讨论】:

    【解决方案2】:

    父类可以调用子类的publicprotected方法,但不能调用private方法。

    【讨论】:

      猜你喜欢
      • 2012-01-11
      • 2013-04-17
      • 2017-07-20
      • 2018-01-13
      • 2014-05-10
      • 2016-09-01
      • 2012-04-25
      • 2011-03-03
      • 2011-02-28
      相关资源
      最近更新 更多