在PHP OOP中,可以通过外部引用对象来调用该对象的父方法吗?
Class ObjectOne {
protected function method() {
// Does something simple
}
}
Class ObjectTwo extends ObjectOne {
protected function method() {
$temp = clone $this;
$this->change_stuff();
if(parent::method()) {
// Do more stuff here
$temp->method();
// This will call this method, not the parent's method.
}
}
protected function change_stuff() {
// Change this object's stuff
}
}
我不能调用parent::method(),因为这将导致当前对象执行它的方法我想要$temp的
已解决
我通过编写另一个函数来解决这个问题,该函数从类内部调用parent::update()
方法:
Class ObjectOne {
protected function method() {
// Does something simple
}
}
Class ObjectTwo extends ObjectOne {
protected function method() {
$temp = clone $this;
$this->change_stuff();
if(parent::method()) {
// Do more stuff here
$temp->update_parent();
// This will call this method, not the parent's method.
}
}
protected function change_stuff() {
// Change this object's stuff
}
protected function update_parent() {
return parent::update();
}
}
$temp->parent::update()
没有意义。
为什么不重新进行parent::update()
而不是$temp->parent::update();
您有两个名为update()
的方法。如果您调用$this->update()
,它将从进行调用的对象中调用该方法。你可以做
parent::update();
这将在ObjectOne
类中运行update()
方法
您可以使用以下语法调用任何受保护的和公共的父方法
parent::method_name();
在您的情况下,这将是:parent::update();