PHP,“其他”总是被处理?

时间:2009-12-09 00:29:31

标签: php codeigniter

我有一个粗略的程序:

if (condition){
  //redirect to some page
}
else{
 echo $some_var;
}

因此,当我测试并且条件为真时,它执行重定向,但也会抛出通知,即存在未定义的变量$ some_var(从数据库中提取并且如果条件为真则不会定义)。

代码继续在if之后评估?这不是我所期望的。

如果你想挖掘,这是实际的代码(它是CodeIgniter,但它主要是自我记录),测试用例是垃圾“礼物代码”,它不在数据库中,因此count_all_results WILL == 0。抛出的通知是$ uses未定义。

    $data['message'] = null;

    //seeing if code is valid
    $submitted_code = $_POST['code'];
    $this->db->where('code', $submitted_code);
    $this->db->from('codes');
    if ($this->db->count_all_results() == 0){
        $data['message'] = "This is not a valid gift code, sorry! You'll need to read our partner blogs, or listen to our favored Twitterers to find a valid code.";
        $this->load->view('submission_form_view', $data);
    }
    else {

    //seeing if code has any uses left
    $this->db->where('code', $submitted_code);
    $this->db->from('redemption_information');
    $used_so_far = $this->db->count_all_results();
    $this->db->select('uses');
    $query = $this->db->get_where('codes', array('code' => $submitted_code));
    foreach ($query->result() as $result)
    {
        $uses = $result->uses;
    }

    echo "Uses: $uses Used so far: $used_so_far <br />";

    if ($uses <= $used_so_far) {
        $this->load->view('over_used_view');
    }
    else
    {
    //these values are auto-escaped, so no worries on SQL injection
    if ($this->db->insert('redemption_information', $_POST)) {
        $data['message'] = "Your order has been taken, thanks for your interest!";
        $this->load->view('success_view', $data);
    }
    else {
        $data['message'] = "There was an error with your order. Please try again.";
        $this->load->view('submission_form_view', $data);
    }
    }
    }

2 个答案:

答案 0 :(得分:4)

解析评估之间存在差异。您收到的通知是解析通知(它正在解析else语句中的变量而没有看到先前的赋值,因此它会抛出通知),但该语句实际上并未已计算如果if条件为真。

答案 1 :(得分:-1)

如果前面的else阻止为if

,则始终会执行false阻止

您可以测试isset($uses)以避免出现警告并实例化$uses的默认值

修改

$uses创建默认值:

    $uses= null;
    foreach ($query->result() as $result)
    {
            $uses = $result->uses;
    }