1

我真的只是对此感到好奇,我不打算实施它,但我确实认为如果出现适当的条件,这将是一个很酷的控制结构。

我有一个布尔数组,代表用户试图查看的数据类型,然后我有一个布尔对象,表示用户是否有权查看该数据。

而不是 if 语句的列表说if(permission and display){show this type},我想我会改为只使用 switch(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;
}

实际上,我只是要创建一个数组并循环遍历它,因为每种情况下的代码都是相同的。

..但我很好奇如果我愿意的话,我将如何让它发挥作用。

4

2 回答 2

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');
   }
}
于 2012-11-17T03:48:36.590 回答
0

它已经被支持 - 只是不包含该break语句,并且匹配的语句之后的每个case块也将被执行,直到break遇到 a 。

此外,该continue语句已switch在 PHP 中的块中得到支持,但其行为类似于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

于 2012-11-17T03:50:14.563 回答