有没有办法从另一个方法停止对象方法执行?

时间:2011-07-08 07:18:35

标签: php oop halt

情况如下:

有一个单独的对象负责生成页面内容,我们可以将其称为内容。另一个对象是它的'parent - Core 对象。 内容对象调用核心方法* Check_parameters_count($ parameters_count)*,因此核心必须检查URI中给定的参数计数是否等于整数在执行此方法时给出($ parameters_count),如果不是 - 核心应生成错误页面并停止执行内容的呈现方法。

如果不使用 if 声明,我有什么方法可以做到这一点?只需在内容类中使用* $ core-> Check_parameters_count(2)*,以简化特定渲染引擎程序员的工作。

一切都应该与此相似:

 class Core {
    public function Check_parameters_count($parameters_count) {
        if (count($this->parameters) != $parameters_count) {
            $this->Show_error(404);
            $this->Stop_executing($content, 'Render');
            //or
            stop($content->Render);
            //or something similar..
        }
    }
}

class Content {
    public function Render() {
        //check given parameters so we could know which page should be rendered and how many parameters should be given
        //...
        //lets say we should have exactly 2 parameters
        $parameters_count = 2;
        //check it
        $core->Check_parameters_count($parameters_count);
        //if parameters count matched - continue method execution
        //...
    }
}

1 个答案:

答案 0 :(得分:1)

抛出exception

您有3个范围:

  • 功能A(功能B的来电者)
  • 功能B
  • 功能A的来电者

如果在函数B中抛出异常,并在函数A的调用者中创建try / catch块,则函数A执行将被异常中断。实际上 - 所有代码执行都将被中断,直到达到相应try / catch块中的级别。