普通网友 2014-10-27 22:44
浏览 45
已采纳

如何检索我在PHP中的另一个交换机案例块中的一个交换机案例块中为变量分配的值?

In PHP is there a way to access the value that I assign to a variable in one case block of a switch statement in another case block in that same switch statement? For instance, I want to access the value I assigned to $task_to_modify in the 'Modify Task' case block in the 'Save Changes' case block below. Here's my code. Any advice would help as I'm new to PHP. Thanks.

$task_to_modify
switch( $_POST['action'] ) {
case 'Add Task':
    $new_task = $_POST['newtask'];
    if (empty($new_task)) {
        $errors[] = 'The new task cannot be empty.';
    } else {
        //$task_list[] = $new_task; //original code
        array_push($task_list, $new_task);
    }
    break;
case 'Delete Task':
    $task_index = $_POST['taskid'];
    unset($task_list[$task_index]);
    $task_list = array_values($task_list);
    break;
case 'Modify Task':
    global $key;
    $key = $_POST['taskid']; //taskid is index of selected task from tasks selection list
    global $task_to_modify;
    $task_to_modify = $task_list[$key];
    set_task_to_modify($task_to_modify);
    echo "modify task case reached. task_to_modify is " . $task_to_modify;
    break;
case 'Save Changes':
    global $task_to_modify;
    if(in_array($new_task, $task_list)) { //if old value is in the list
        $index = array_search($new_task, $task_list); //return index # of old value
        $task_list[$index] = $task_to_modify; //replaces old value with newly entered value
        unset($task_to_modify); //deletes var so original form will show
    }
    break;
case 'Cancel Changes': //works correctly
    echo 'no changes saved';
    unset($task_to_modify);
    break;

}

  • 写回答

1条回答 默认 最新

  • doujiao9574 2014-10-27 22:48
    关注

    PHP has no scope for each block. So the variable is available in the 'modify task' block and in the 'save changes' block, since they share the same scope. You might also take a look here to understand it a little bit better.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 一道python难题2
  • ¥15 一道python难题
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备