不同PHP版本之间的未定义变量问题


Undefined variable Issue Between Different PHP Version?

我使用XAMPP 1.7.2 (PHP 5.3)在winxp localhost上进行开发。有一个函数运行得很好。来自CodeIgniter模块

function get_cal_eventTitle($year, $month){
        $this->db->where('eventYear =', $year);
        $this->db->where('eventMonth =', $month);
        $this->db->select('eventTitle');
            $query = $this->db->get('tb_event_calendar');
        $result = $query->result(); 
        foreach ($result as $row)
        {
            $withEmptyTitle = $row->eventTitle;         
            //echo $withEmptyTitle.'<br>';
            $noEmptyTitle = str_replace(" ","%20",$withEmptyTitle);
            $withUrlTitle = '<a href='.base_url().'index.php/calendar/singleEvent/'.$year.'/'.$month.'/'.$noEmptyTitle.'/'.'>'.$withEmptyTitle.'</a>';         
            //echo $withUrlTitle.'<br>';
            $row->eventTitle = $withUrlTitle;          
        }
        return $result;
    }

当我上传我的代码到远程服务器(PHP 5.2.9)。它显示错误如下,

withEmptyTitle未定义变量

A PHP Error was encountered
Severity: Notice
Message: Undefined variable: withUrlTitle
Filename: models/calendar_model.php
Line Number: 54 // $withEmptyTitle = $row->eventTitle;  

但是当我启用echo $withEmptyTitle.'<br>';的注释时。在远程服务器上运行良好。

假设withEmptyTitle回显到Apr运行事件这里

我不知道为什么?你能给我一些建议来解决这个问题吗?谢谢你的建议。

您看到的可能不是错误,而是警告

PHP可能会抛出警告,因为您使用了尚未初始化的变量。听起来,您的本地开发PHP安装可能已经禁用了警告消息,而您的活动服务器启用了它们。(事实上,最好的做法是反过来!)

在这种情况下,如果eventTitle属性返回为未设置,则$withEmptyTitle = $row->eventTitle;可能没有初始化$withEmptyTitle变量。然后,当您尝试在str_replace()调用中使用该变量时,它将落在下面一行并抛出警告。

可以通过以下方式避免此警告:

  • 在PHP.ini
  • 中关闭警告信息
  • 在程序中执行ini_set()将其关闭
  • 使用isset($withEmptyTitle)检查变量是否在实际使用之前设置。
  • 确保$row确实包含eventTitle属性(在您的程序的上下文中,如果它丢失,它可能意味着坏的数据或不正确的数据库表设置?在任何情况下,您都可以更改SQL查询以使用IFNULL()或至少确保显式查询该字段。
[编辑]

我看到你编辑了这个问题。我特别注意以下内容:

Line Number: 54 // $withEmptyTitle = $row->eventTitle;  

我注意// ....这是否意味着该行被注释掉了??你有没有在服务器上找到一份注释了这一行的副本?这就解释了为什么你会收到警告了!