我有一个父类,其代码如下:
class ParentClass {
public function parentMethod()
{
if (childMethodExist()) {
$this->childMethod();
}
}
}
class ChildClass extends ParentClass {
public function childMethod()
// statement 1
// statement 2
}
}现在我想打电话给parentMethod(),它将给childMethod()打电话。我的问题是,我这样做是否正确(我已经得到了$this->childMethod();在VSCode中的错误)。但是代码和我预期的一样工作。
发布于 2022-02-05 02:02:19
childMethodExist是什么?那应该是method_exists($this, 'childMethod'),我想说?
但是,一个更好的方法通常是让孩子的parentMethod过载,比如:
class ChildClass extends ParentClass {
public function parentMethod() {
// some child specific code might go here
parent::parentMethod();
// and some child specific code might go here
}
}然后,只要你有父母或孩子的东西,你总是打电话给$object->parentMethod(),它就会起作用。这样,您的父对象根本不了解子对象(它不应该知道!),但是仍然使用它的实现,因此可以防止代码重复。
https://stackoverflow.com/questions/70994681
复制相似问题