0

情况如下:

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

有什么方法可以在不使用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
        //...
    }
}
4

1 回答 1

1

抛出异常

您有 3 个作用域:

  • 函数 A(函数 B 的调用者)
  • 功能 B
  • 函数 A 的调用者

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

于 2011-07-08T08:26:18.950 回答