PHP重写父方法,不直接调用

时间:2017-10-16 10:26:05

标签: 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()将从原始Post类调用,而不是子Event类。是否有任何聪明的方法来覆盖父方法,因此它将被对象使用?或者唯一的选择是修改被调用的方法,在本例中为save()

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
    }
}

1 个答案:

答案 0 :(得分:1)

我没有看到您的代码有任何问题,一切都应该正常工作,尝试在您的方法中执行一些var_dump并查看输出将是什么