试图定义Undefined Variable错误


trying to define an, Undefined Variable error

我收到一个未定义的变量错误,我尝试添加var $nx = '';,但没有帮助。我是不是错过了什么注意:第55行/home/social/public_html/kernel/parser.php中的未定义变量nx

                while (!feof($f)) {
                    $s = chop(fgets($f,4096));
                        if ($s == '') continue;
                        if (substr($s,0,5) == '<!--[') {
                                if ($nx != '') $this->templ[] = $nx;
                                $this->templ[] = $s;
                                $nx = '';
                                }
                        elseif (substr($s,0,5) == '<?php') {
                                if ($nx != '') $this->templ[] = $nx;
                                $nx = $s;
                                }
                        else 
////// LINE 55                  $nx .= ($nx != '' ? "'n" : '').$s;
                        if (substr($nx,-2) == '?>') {
                                $this->templ[] = $nx;
                                $nx = '';
                                }
                        }

您在if块中定义了var。

这是正确的代码:

                $nx = '';
                while (!feof($f)) {
                $s = chop(fgets($f,4096));
                    if ($s == '') continue;
                    if (substr($s,0,5) == '<!--[') {
                            if ($nx != '') $this->templ[] = $nx;
                            $this->templ[] = $s;
                            $nx = '';
                            }
                    elseif (substr($s,0,5) == '<?php') {
                            if ($nx != '') $this->templ[] = $nx;
                            $nx = $s;
                            }
                    else 
                            $nx .= ($nx != '' ? "'n" : '').$s;
                    if (substr($nx,-2) == '?>') {
                            $this->templ[] = $nx;
                            $nx = '';
                            }
                    }

因为您在if块中定义它,但假设它存在于else块中,即当if与条件不匹配时使用什么!

在这一行之后初始化它,这样if、elseif和else都将变量初始化为空字符串(如您所需):

$s = chop(fgets($f,4096));
$nx = '';

或者在整个块之前全部

编辑:

但更好的解决方案是告诉$nx应该来自什么,因为您假设它存在于任何地方,并且它与空字符串不同。那么,它应该装什么?无论如何,要确保,无论它必须包含什么,它都存在。第二次阅读你的代码时,我发现在很多地方你都希望它不是一个空字符串。。

此外,您没有提到您的代码是否是函数的一部分。如果是这种情况,请考虑该函数有一个作用域,因此如果您在函数外部定义它,则需要将其提供给该函数,否则该函数将看不到它。