我有两个班家长和孩子:PHP重载父类的方法是不直接调用
class Post
{
public function save()
{
$this->update_data();
$this->custom_updates();
$this->load();
}
protected function custom_updates() { /* empty */ }
}
class Event extends Post
{
protected function custom_updates()
{
//perform custom updates specific for Event objects
}
}
$Event = new Event();
$Event->save();
当我执行上面的代码的方法custom_updates()将由原来的邮政类被称为
,不是孩子事件类。有没有什么聪明的方法来覆盖父方法,所以它会被对象使用?或者,唯一的选择是修改被调用的方法,在这个例子中保存()
class Event extends Post
{
public function save()
{
$this->update_data();
$this->custom_updates();
$this->load();
}
protected function custom_updates()
{
//perform custom updates specific for Event objects
}
}
*“当我执行上面的代码时,方法'custom_updates()'将从原始Post类调用,而不是子类Event类。” - 这是不正确的。调用'$ this'的类中的'custom_updates()'方法。检查出来:https://3v4l.org/SFaLU这是继承在PHP中的工作原理。 – axiac
您发布的代码覆盖父方法。这基本是一个基本的操作原则。请再次检查。 –
被调用的方法将是压倒一切的子方法 - [Demo](https://3v4l.org/leZ3X) –