升级PHP版本时注意事项


notices when upgrade the php version

我正在使用一个类与矩阵进行一些计算,在这种情况下:获取每列的和。

sum输出是正确的,如果我隐藏通知,问题就解决了,但从逻辑上讲,我更喜欢更正。

在PHP 5.3中,我在这个函数中得到一些注意:

Notice: Undefined offset: 0 
Notice: Undefined offset: 0 
Notice: Undefined offset: 1 
脚本

function sum()
    {
        foreach($this->numbers as $i => $rows)
        {
            foreach($rows as $j => $number)
            {
                $this->sum[0][$j] += $number; //notices here
            }
        }
        $the_sum = new matrix($this->sum, 1, $this->get_num_columns());
        return $the_sum;
    }
矩阵:

1     | 4
0.25  | 1

var_dump($this->numbers);
array
  0 => 
    array
      0 => int 1
      1 => float 4
  1 => 
    array
      0 => float 0.25
      1 => int 1

 $this->get_num_columns() // 2

有什么建议吗?

谢谢

是的,出现该通知是因为您要添加数字的变量中没有初始值。您应该检查该数字是否存在,并在向其添加数字之前对其进行初始化。(注意,这不会改善结果,但初始化变量是一个很好的实践)。

function sum()
    {
        foreach($this->numbers as $i => $rows)
        {
            foreach($rows as $j => $number)
            {
                if (!isset($this->sum[0][$j])) $this->sum[0][$j] = 0;
                $this->sum[0][$j] += $number; //no notices here
            }
        }
        $the_sum = new matrix($this->sum, 1, $this->get_num_columns());
        return $the_sum;
    }

不相关的考虑点

  • 正确的命名标准规定类名应该大写,以区别于函数。所以你应该把你的类命名为Matrix而不是matrix
  • 如果你有机会,一个更好的解决方案是用0预先填充你的数组。array_fill()做得很好。