2011-07-08 79 views
0

情況如下:有什麼方法可以從另一種方法停止對象方法的執行嗎?

有一個單獨的對象,它負責生成網頁的內容,我們可以把它叫做內容。另一個對象是它的'父母 - 核心對象。 內容對象調用核心方法* Check_parameters_count($ parameters_count)*,所以核心有檢查,如果給定參數的URI數等於在執行這個方法($ parameters_count)給出的整數,如果不是 - 核心應該生成錯誤頁面並停止執行內容的渲染方法。

有沒有什麼辦法可以做到這一點,而不使用如果聲明?只需在內容類中使用* $ 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

拋出一個exception

你有3個範圍:

  • 功能A(函數B的調用者)
  • 功能B
  • 來電顯示的功能的

如果你扔在功能B異常,並在函數A的調用者中創建一個try/catch塊,函數A的執行將被異常中斷。事實上 - 所有的代碼執行都會被中斷,直到被相應的try/catch塊封裝。

+0

好主意:)這正是我一直在尋找的。 這是第一次例外對我有用,因爲我總是停止使用它們,因爲同時缺少多錯誤投擲。 –

相關問題