2012-11-17 74 views
1

我真的只是好奇這一點,我不打算實施它,但我認爲這將是一個很酷控制結構使用應該適當的條件出現。設置開關()不會中斷匹配的情況下,而是繼續到所有匹配的案例

我有一個布爾值數組,表示用戶正在嘗試查看哪些類型的數據,然後我有一個布爾值對象,表示用戶是否有權查看該數據。

而不是if語句列表if(permission and display){show this type},我認爲我會反而只是使用開關(true),實際上寫入相同數量的代碼,但格式化好一點,只要我能得到一個switch語句到continue; ..那本來很酷。

switch(true){ 
    case ($processPermissions->history->view) && ($display['history'] !== false): 
     $application['history'] = $this->getHistory(); 
     continue; 

    case ($processPermissions->notepad->view) && ($display['notepad'] !== false): 
     $application['notepad'] = $this->notepad('get'); 
     continue; 

    case ($processPermissions->documents->view) && ($display['documents'] !== false): 
     $application['documents'] = $this->documents('get'); 
     continue; 

    case ($processPermissions->accounting->view) && ($display['accounting'] !== false): 
     $application['accounting'] = $this->accounting('get'); 
     continue; 

    case ($processPermissions->inspections->view) && ($display['inspections'] !== false): 
     $application['inspections'] = $this->inspections('get'); 
     continue; 

    case ($processPermissions->approvals->view) && ($display['approvals'] !== false): 
     $application['approvals'] = $this->approvals('get'); 
     continue; 
} 

實際上,我只是要創建一個數組並循環,因爲代碼對於每種情況都是相同的。

..但我很好奇我會如何能夠得到這個工作,如果我想。

回答

0

好像很多無意義的重複,當你可以有像

$stuff_to_check = array('history', 'notepad', 'documents', 'accounting', etc....) 
foreach($stuff_to_check as $thing) { 
    if ($processPermissions->$thing->view && ($display[$thing] !== false)) 
     $applications[$thing] = $this->document('get'); 
    } 
} 
+0

準確地說,我在帖子的最後一句話中要說的是:P這都是好奇心 –

0

它已經支持的 - 只是不包括匹配會被執行的一前一後break語句和每一個case塊直到遇到break

此外,continue聲明已在PHP的switch塊中得到支持,但其行爲類似於break

有關更多詳細信息,請參閱switch的文檔。

$value = 2; 
switch ($value) { 
    case 0: 
     // not executed 
    case 1: 
     // not executed 
    case 2: 
     // executed 
    case 'whatever': 
     // executed 
     break; 
    case 'foo': 
     // not executed 
     break; 
    default: 
     // not executed 
} 

有關更多詳細信息,請參閱switch的文檔。

+0

事實上,這是一件事情,但如果您有第一個案件的$允許並且不會中斷,第二種情況的權限,即使大小寫返回false,它仍然會繼續。 'switch(true){case true:echo「this should work!」; case false:echo「This should not,but it will!」;打破; }' –

+0

啊,有你 - 從字面上來說只是一種用更多代碼來編寫'if'語句的方法嗎?不確定我同意這會很酷,但如果我們都以同樣的方式看待這個世界將是一個無聊的地方:) – Kelvin

+1

也許有一天我會在代碼混淆比賽中使用它,或者讓同事從零開始他們的頭。誠實地說,它可能沒有任何有效的用處,但它至少在一個小時內一直存在,這是我提出問題的門檻。 –

相關問題