在父类中包装子函数

时间:2015-03-26 10:42:48

标签: php inheritance yii parent-child

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

}

1 个答案:

答案 0 :(得分:0)

接近它的最佳方式是:

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