【问题标题】:Wrap child function in parent class在父类中包装子函数
【发布时间】:2015-03-26 10:42:48
【问题描述】:

PHP 中有没有办法在父类中包装子函数? 我有 cron 作业命令,并且想在每个命令执行结束时添加一个方法。像这样:

public class child extends parent {

    public function run($args) {
        //something here
    }
}




public class parent extends CConsoleCommand {

    public function run($args) {
        child_run_function($args);
        $this->sendExecutionStatusEmail();
    }

    public function sendExecutionStatusEmail() {
        //some code here
    }

}

【问题讨论】:

  • 检查这个链接,也许有帮助?stackoverflow.com/questions/9525208/…
  • @AhmedZiani 这个例子与我想做的相反
  • parent 构造函数中使用 'composition' 并注入 'child' 可能更容易,而不是子扩展父级。然后,当您调用 parent->run(args) 时,它将执行 _child->run(args) 然后进行处理。我没有看过“运行”方法,所以这只是关于如何调查它的一些想法。
  • 我建议你检查一下 yii 活动记录类是如何工作的。当你保存一条记录时,调用 save 方法,它会触发过滤器、验证、保存前后等父方法,而对子类没有任何实现

标签: php inheritance yii parent-child


【解决方案1】:

最好的方法是这样的:

class Child extends Parent {

    public function run($args)
    {
        // Child specific code

        // Call the parent's run function
        parent::run($args); // Note: parent here does not refer to a class parent, it's a PHP keyword which means the parent class
    }

}

class Parent extends CConsoleCommand {

    public function run($args)
    {
        $this->sendExecutionStatusEmail();
    }

    public function sendExecutionStatusEmail()
    {
        // Something here
    }

}

编辑

或者您可以做的是将一些功能写入父运行函数,以检查函数的存在并在触发电子邮件之前调用它。比如:

class Child extends Parent {

    public function yourMethodName()
    {
        // Do something
    }

}

class Parent extends CConsoleCommand {

    public function run($args)
    {
        // If the method yourMethodName exists on 'this' object
        if (method_exists($this, 'yourMethodName'))
        {
            // Call it
            $this->yourMethodName();
        }

        // The rest of your code
        $this->sendExecutionStatusEmail();
    }

    public function sendExecutionStatusEmail()
    {
        // Something here
    }

}

这样你可以在子类上创建一个匹配yourMethodName的方法,当调用run方法时(从父类继承),如果存在yourMethodName就会被调用。

【讨论】:

  • 是的,但我想包装子函数而不更改它们
  • @dzona 查看我的更新答案,这有帮助吗?
  • 你有没有注意到 child 和 parent 都有相同的方法名称,称为 run?您的代码将进行无休止的递归,例如我写的:) 即使您正确调用子方法,使用ReflectionClass 它也会再次产生杀手循环。由于这个例子是在Yii框架中,我可能可以覆盖控制台运行器并在命令执行后添加自定义函数,但我不想和你讨论,有没有解决这个问题的纯PHP解决方案
  • 我不这么认为。如果您在子级中省略 run 方法,它将继承您想要的 run 的父类版本。如果您决定覆盖子类中的 run 方法,则可以。但是如果你想保留父类的功能,你可以在你的实现中的某个地方调用parent::run()。我对 Yii 不太熟悉,但希望这对你有用。
猜你喜欢
  • 2019-11-03
  • 1970-01-01
  • 2019-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-20
  • 1970-01-01
相关资源
最近更新 更多