是否可以在同一个if块中运行多个elseif块?

时间:2012-05-21 20:39:43

标签: php if-statement

$foo=1;

function someFunction(){
  if($foo==0){ //-------Will test, won't execute
    bar();
  }elseif($foo==1){ //--Will test, and execute
    baz();
  }elseif($foo==2){ //--Doesn't test
    qux();
  }elseif($foo==3){ //--Doesn't test
    quux();
  }else{ //-------------Doesn't test
    death();
  } //------------------The program will skip down to here.
}

假设baz()改变了$ foo的值,每次都不同。我希望我的代码在第一个之后继续测试elseif / else语句,如果它们是真的则运行它们。

我不想再次运行整个函数,(即我不在乎$ foo = 0还是1)。我正在寻找像“继续”这样的东西。无论如何,请告诉我这是否可行。谢谢。 :)

编辑**我的代码实际上比这更复杂。我只是为了理论而放下一些代码。我想要的只是脚本,以便继续测试它通常不会的位置。

4 个答案:

答案 0 :(得分:5)

如果我理解正确,您希望每个连续elseif执行此操作,无论之前的if / elseif是否匹配,但您还需要运行一些代码<\ n if / elseif匹配的em> none 。在这种情况下,如果其中一个匹配并使用$matched,则可以将标记true设置为if

<?php
$foo=1;
function someFunction(){
  $matched = false;
  if($foo==0){
    bar();
    $matched = true;
  }
  if($foo==1){ //--This elseif will get executed, and after it's executed,
    baz();
    $matched = true;
  }
  if($foo==2){
    qux();
    $matched = true;
  }
  if($foo==3){
    quux();
    $matched = true;
  }
  if(!$matched){ /* Only run if nothing matched */
    death();
  }
}

如果您还希望能够跳到最后,请使用goto(但see this first):

<?php
$foo=1;
function someFunction(){
  $matched = false;
  if($foo==0){
    bar();
    $matched = true;
    goto end: // Skip to end
  }
  if($foo==1){ //--This elseif will get executed, and after it's executed,
    baz();
    $matched = true;
  }
  if($foo==2){
    qux();
    $matched = true;
  }
  if($foo==3){
    quux();
    $matched = true;
  }
  if(!$matched){ /* Only run if nothing matched */
    death();
  }
  end:
}

答案 1 :(得分:3)

我不知道这是不是你的意思,但你可以使用开关声明:

$foo=1;
function someFunction(){
  switch($foo==0){
    case 0:
        bar();
    case 1:
        baz();
    case 2:
        qux();
    case 3:
        quux();
    default:
        death();
}

请注意,每种情况都不会中断。

答案 2 :(得分:1)

如果只是一堆ifs,你就不能使用其他......

答案 3 :(得分:-1)

//此回复不正确。见下面的评论。谢谢!

我不是专家,但按照我理解的方式,他们会继续跑步。如果将来您正在编写一组elseif()语句,并且想要在一个语句出现时离开该系列,则使用break命令。另请参阅switch()

如果我错了,我绝对愿意纠正。