2017-10-16 47 views
-4

我有两个班家长和孩子: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 
    } 
} 
+1

*“当我执行上面的代码时,方法'custom_updates()'将从原始Post类调用,而不是子类Event类。” - 这是不正确的。调用'$ this'的类中的'custom_updates()'方法。检查出来:https://3v4l.org/SFaLU这是继承在PHP中的工作原理。 – axiac

+0

您发布的代码覆盖父方法。这基本是一个基本的操作原则。请再次检查。 –

+0

被调用的方法将是压倒一切的子方法 - [Demo](https://3v4l.org/leZ3X) –

回答

1

我看不出有任何问题与您的代码,一切都应该是工作,尝试做一些var_dump在你的方法并看看输出是什么

+0

我的不好,我之前测试过,它没有工作。现在,当我再试一次时,它的效果非常好。我的错误和我为愚蠢的问题道歉。 – ArturoO

+0

@ArturoO我们都可以通过犯错来学习 – kellymandem