0

我是 php 新手,我在 php 书中做了一个例子。在那里我得到了下面notice。如何防止这个通知?

<?php
require_once('AddingMachine.php');
$arrayofnumbers = array(100,200);
$objectname = new AddingMachine();
$objectname->addNumbers($arrayofnumbers);
?>

<?php
Class AddingMachine
{
private $total = 0;
function addNumbers(array $numbers)
{{
for($i=0;$i<=sizeof($numbers);$i++)
{
    $this->total = $this->total + $numbers[$i];
}
   echo $this->total;
 }
}
}
4

2 回答 2

2

改变你的循环

for($i=0; $i <= sizeof($numbers); $i++)

for($i=0; $i < sizeof($numbers); $i++)

也最好使用count.

for($i=0; $i < count($numbers); $i++)
于 2013-03-27T06:37:58.240 回答
1

问题在于<= sizeof($numbers)( 等于count($numbers)。它会给你数组元素的总数,它总是比最大​​索引多一,因为数组从 0 开始计数。

只需将其替换为<=<可以了。

于 2013-03-27T06:37:38.557 回答