【问题标题】:Assign result of function within switch to variable将 switch 内函数的结果分配给变量
【发布时间】:2013-11-12 14:33:29
【问题描述】:

这里有一些伪代码(写的不正确,我的 ? 点是变量,不是开关):

switch ($action) {

case "1":
//this is a function

case "2":
//this is a function

//etc.
}

这个应该怎么写:

$variable = 案例 1 中的函数结果。

【问题讨论】:

    标签: php switch-statement


    【解决方案1】:

    您的 switch 陈述是错误的。它要求每个案例之间有一个break关键字

    $action = 1;
    $result = "Success";
        switch ($action) {
    
        case 1:
        $variable = $result;
        echo $variable;//prints Success
    
        //this is a function
        break; // like this
    
        case 2:
        //this is a function
        break;//
        //etc.
        }
    

    【讨论】:

    • 我知道。它是一个非常简化的版本。我只需要知道如何将案例中函数的结果分配给变量。
    • 我在您的代码中看不到任何功能。但是,请参阅我修改过的代码。
    • switch case 不是函数,也没有返回值。开关本身也没有返回值。
    【解决方案2】:

    只需运行函数(您也可以传入 args)作为 case / break 块中代码的一部分,如下所示:

    $action = 1;
    
        switch ($action) {
    
        case 1:
            $variable = someFunctionOne();
    
        break; 
    
        case 2:
            $variable = someOtherFunctionTwo();
        break; 
        //etc.
        }
    

    【讨论】:

      【解决方案3】:

      如何改变php切换的结果。 例如:

      <?php
      //variables of cases
      $var_1 = 1;
      $var_2 = 2;
      $var_3 = 3;
      $var_0 = 0;
      //end variables of cases
      //action variable
      $action = 10;
      //end action variable
          //start switch
      switch ($action) {
        case "1":
          echo "$var_1;";
          break;
        case "2":
          echo "$var_2;";
          break;
        case "3":
          echo "$var_3;";
          break;
        default:
          echo "$var_0;";
      }
      
      //receives the value of the switch.
      $switch_result = get_result_case;
      //in this my example I need to enter the value of the case in a variable.
       ?>

      在我的示例中,我需要在变量中输入 case 的值。

      【讨论】:

      • 建议:那里的代码 sn-p 非常没用。并添加语言标识符以突出显示代码并使其更好地阅读
      猜你喜欢
      • 2022-07-02
      • 2010-10-02
      • 1970-01-01
      • 2020-10-05
      • 1970-01-01
      • 1970-01-01
      • 2011-10-22
      • 2021-08-21
      • 2021-02-04
      相关资源
      最近更新 更多