普通网友 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 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化