PHP - 重新定义方法并调用相同方法的祖先版本

Seb*_*oli 5 php inheritance

我想重新定义一个方法,并调用我祖先的版本,而不是我父母的版本.

这是一个简短的例子:

// This class is autogenerated and I am not supposed to modify it.
class myParent extends myGrandparent {

  function doSomething() {
    doA();
    doB();
    doC();
    parent::doSomething();
  }

}

// Here is my code
class myClass extends myParent {

  function doSomething() {
    // doA();    // I don't want to do A anymore.
    // doB();    // Neither B.
    doC();       // But I want to keep doing C.
    parent::doSomething();      // OOPS!!  This does A and B (and C again)!
  }

}
Run Code Online (Sandbox Code Playgroud)

如何直接调用myGrandparent的方法,而不是myParent?

Chr*_*sNY 2

不确定用例是什么,但除非我误解了问题/问题(很有可能),否则您完全可以调用任何任意祖先(公共或受保护)方法,无论其之间被重写了多少次,甚至是默认方法任何祖先成员属性(公共或受保护)的值,即使它也被覆盖。例如,对于类层次结构:

Papa > Mama > Baby > Infant,其中方法sayWhat()和实例变量$el在每个后代类中都被重写,您可以从 Infant 调用任何祖先的 sayWhat 方法,并访问不同的祖先默认属性值:

class Papa {
  protected $el = 'PapaEl';
  protected function sayWhat($className = null) {
    if (!$className) {
      $className = get_class($this);
    }
    $classVars = get_class_vars($className);
    $localEl = $classVars['el'];
    echo "<h2>What is PAPA!. El: [$localEl]</h2>";
  }
}

class Mama extends Papa {
  protected $el = 'MamaEl';
  protected function sayWhat() {
    echo "<h2>What is MAMA! El: [$this->el]</h2>";
  }
}

class Baby extends Mama {
  protected $el = 'BabyEl';
  protected function sayWhat() {
    echo "<h2>What is Lil' Baby!! El: [$this->el]</h2>";
  }
}

class Infant extends Baby {
  protected $el = 'InfantEl';
  protected function sayWhat($className) {
    Papa::sayWhat($className);
  }

  public function mySayWhat($className) {
    $this->sayWhat($className);
  }
}
$i = new Infant();
$i->mySayWhat('Mama');
Run Code Online (Sandbox Code Playgroud)

输出:

什么是爸爸!艾尔:[妈妈艾尔]

不确定它有什么价值,但如果有人有要求,这似乎是非常可行的......