【问题标题】:Assigned variable empty outside of switch statement PHP在switch语句PHP之外分配的变量为空
【发布时间】:2015-04-26 00:04:59
【问题描述】:
public function store($feed) 
    {
        switch($feed)
        {
            case 'full':
                $coupons = json_decode(file_get_contents('path-to-json-feed'), true);
                break;
            case 'incremental':
                $coupons = json_decode(file_get_contents('path-to-different-json-feed'), true);
                break;
         }
        var_dump($coupons);die();
        $this->Deal_model->updateAllDeals($coupons);
        echo 'Coupons Updated';     
    }

我正在尝试为$coupons 赋值,但var_dump($coupons) 返回一个空数组。

【问题讨论】:

  • 那么你的问题是?
  • 如果$feed 既不是“满”也不是“增量”,那么$coupons 将是空的……那么你验证过$feed 的值了吗?
  • 对不起第一次发帖,我把它搞砸了。 $coupons 变量在 var_dumped 时返回为空数组。
  • 如果我 var_dump $feed 它是一个字符串“增量”
  • @mjamieson 的 exact 输出是什么:var_dump($feed);(从源代码中获取输出)?

标签: php variables scope switch-statement


【解决方案1】:

我建议你添加一个default,以防$feed 不是fullincremental

如果这是您的实际代码,我不确定是否有一个名为 path-to-json-feed 的文件,但它似乎应该是其他内容,例如 JSON 文件/提要的实际路径。

path-to-json-feed 替换为实际文件,然后尝试使用下面的代码,看看会得到什么。

public function store($feed) 
{
    switch($feed)
    {
        case 'full':
            $coupons = json_decode(file_get_contents('path-to-json-feed'), true);
            break;
        case 'incremental':
            $coupons = json_decode(file_get_contents('path-to-json-feed'), true);
            break;
        default:
            $coupons = json_decode(file_get_contents('path-to-json-feed'), true);
            break;
     }
    var_dump($coupons);
    die(); // DEBUGGING
    $this->Deal_model->updateAllDeals($coupons);
    echo 'Coupons Updated';     
}

【讨论】:

  • 是否可以帮助其他人明确此代码仅用于调试目的而不是有效的答案?我很欣赏 'die()' 声明是一个很大的线索。 :)
  • 您应该结合任何具有重复内容的相关案例 - DRY
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-29
相关资源
最近更新 更多