0

如果我没记错的话,我曾经第一次在 if 语句或条件循环块中使用新的 PHP 变量。我想说的是如下。

<?php

    for($i=0;$i<10; $i++)
    {
        $total += $i;
        $concat .= $i;
    }
 ?>

但是今天,当我查看错误日志时,它说 $total 和 $concat 是未定义的变量。然后我写这个

    $total = 0;
    $concat="";   
    for($i=0;$i<10; $i++)
    {
        $total += $i;
        $concat .= $i;
    }
 ?>

它可以正常工作。为什么?只求好奇。

4

2 回答 2

4

这是因为:

$total += $i;
$concat .= $i;

实际上意味着:

$total  = $total+$i;
$concat = $concat.$i;

第一次执行循环,$total并且$concat未定义。所以你得到了错误。

更多细节:

在循环的第一次运行期间,您正在编写

$total = the value of undefined $total + $i;

现在,总计已定义。$concat 也一样。

于 2013-03-20T21:35:00.343 回答
1

变量需要在使用前声明。根据您的错误报告,您不会看到错误。

于 2013-03-20T21:36:51.223 回答