在 PHP 中使用 类 组合两个或多个函数

Combining two or more function using classes in PHP

我有两个 php classes.

Class classOne {

  private $stuff;
  public $stuff2;

  public function init(){
    dosomestuff;
  } 

}

&

Class classTwo extends classOne {

  private $stuff;
  public $stuff2;

  public function init(){ #This function is overriding the native classOne method init;
    dosomeotherstuff;
  } 

}

当我调用函数init时

$obj = new classTwo();
$obj -> init(); #dosomeotherstuff

PHP 解释器将 dosomeotherstuff 正如任何人所期望的那样,因为 class两个 class 声明了对方​​法 init 的覆盖;

相反,有没有办法结合第一个 init 和第二个 init 的效果,以获得类似的东西?

$obj = new classTwo();
$obj -> init(); #dosomestuff, #dosomeotherstuff

非常感谢

在覆盖的函数中你可以调用基函数:

public function init() {
    parent::init();
    // your normal code
}

使用父子方法:

Class classTwo extends classOne {

  private $stuff;
  public $stuff2;

  public function init(){ #This function is overloading the native classOne method init;
    parent::init();
    dosomeotherstuff;
  } 

}