每个人都会遇到语法错误。即使是经验丰富的程序员也会出现拼写错误。对于新人来说,这只是学习过程的一部分。然而,通常很容易解释如下错误消息:

PHP解析错误:语法错误,在index.php第20行中出现意外的“{”

意想不到的符号并不总是真正的罪魁祸首。但是行号给出了从哪里开始查找的大致概念。

总是查看代码上下文。语法错误通常隐藏在前面提到的或前面的代码行中。将您的代码与手册中的语法示例进行比较。

但并不是所有情况都是一样的。但是有一些通用的步骤可以解决语法错误。 本文总结了常见的陷阱:

Unexpected T_STRING Unexpected T_VARIABLE Unexpected '$varname' (T_VARIABLE) Unexpected T_CONSTANT_ENCAPSED_STRING Unexpected T_ENCAPSED_AND_WHITESPACE Unexpected $end Unexpected T_FUNCTION… Unexpected {Unexpected }Unexpected (Unexpected ) Unexpected [Unexpected ] Unexpected T_IF Unexpected T_FOREACH Unexpected T_FOR Unexpected T_WHILE Unexpected T_DO Unexpected T_PRINT Unexpected T_ECHO Unexpected T_LNUMBER Unexpected ? Unexpected continue (T_CONTINUE)Unexpected continue (T_BREAK)Unexpected continue (T_RETURN) Unexpected '=' Unexpected T_INLINE_HTML… Unexpected T_PAAMAYIM_NEKUDOTAYIM… Unexpected T_OBJECT_OPERATOR… Unexpected T_DOUBLE_ARROW… Unexpected T_SL… Unexpected T_BOOLEAN_OR… Unexpected T_BOOLEAN_AND… Unexpected T_IS_EQUAL Unexpected T_IS_GREATER_OR_EQUAL Unexpected T_IS_IDENTICAL Unexpected T_IS_NOT_EQUAL Unexpected T_IS_NOT_IDENTICAL Unexpected T_IS_SMALLER_OR_EQUAL Unexpected < Unexpected > Unexpected T_NS_SEPARATOR… Unexpected character in input: '\' (ASCII=92) state=1 Unexpected 'public' (T_PUBLIC) Unexpected 'private' (T_PRIVATE) Unexpected 'protected' (T_PROTECTED) Unexpected 'final' (T_FINAL)… Unexpected T_STATIC… Unexpected T_CLASS… Unexpected 'use' (T_USE) Unexpected T_DNUMBER Unexpected , (comma) Unpexected . (period) Unexpected ; (semicolon) Unexpected * (asterisk) Unexpected : (colon) Unexpected ':', expecting ',' or ')' Unexpected & (call-time pass-by-reference) Unexpected .

密切相关的参考文献:

这个错误在PHP中意味着什么?(运行时错误) 解析错误:语法错误,意外的T_XXX 解析错误:语法错误,意外的T_ENCAPSED_AND_WHITESPACE 解析错误:语法错误,意外的T_VARIABLE 这个符号在PHP中是什么意思?(语言标记) 这些“聪明”的引号对PHP毫无意义

And:

php.net上的PHP手册和它的各种语言标记 或者维基百科关于PHP的语法介绍。 最后是我们的php标签维基。

虽然Stack Overflow也欢迎新手程序员,但它主要针对的是专业编程问题。

回答每个人的编码错误和狭窄的拼写错误被认为是离题了。 因此,在发布语法修正请求之前,请花时间遵循基本步骤。 如果你仍然必须这样做,请展示你自己的解决方案,尝试修复,以及你对看起来或可能错误的思考过程。

如果您的浏览器显示错误消息,如“SyntaxError: illegal character”,那么它实际上不是php相关的,而是javascript语法错误。


供应商代码引起的语法错误:最后,考虑一下,如果语法错误不是由编辑代码库引起的,而是在外部供应商包安装或升级之后引起的,则可能是由于PHP版本不兼容造成的,因此请根据平台设置检查供应商的要求。


当前回答

意想不到的美元结束

当PHP谈到“意外的$end”时,这意味着您的代码在解析器期望更多代码时结束了。(如果从字面上理解,这个信息有点误导。它不是关于一个名为“$end”的变量,就像新来者有时认为的那样。它指的是“文件的结束”,EOF。)

原因:代码块/和函数或类声明的{和}不平衡。

它几乎总是缺少一个}花括号来关闭前面的代码块。它的意思是,解析器希望找到一个结束},但实际上到达了文件的末尾。

同样,使用适当的缩进来避免此类问题。 使用带有括号匹配的IDE,找出}错误的地方。 在大多数ide和文本编辑器中都有快捷键: NetBeans, PhpStorm, Komodo: Ctrl[和Ctrl] Eclipse, Aptana: CtrlShiftP Atom, Sublime: Ctrlm - Zend Studio Ctrlm Geany, notepad++: CtrlB - Joe: CtrlG - Emacs: C-M-n - Vim: %

大多数ide还突出显示匹配的大括号、方括号和圆括号。 这使得检查它们的相关性变得非常容易:

无端接的表达式

对于未结束的表达式或语句,也会出现意外的$end语法/解析器错误:

$var = func(1, ?>EOF

因此,首先查看脚本的末尾。拖尾;在任何PHP脚本中,最后一条语句通常是多余的。但你应该有一个。正是因为它缩小了这些语法问题的范围。特别是在您发现自己在脚本末尾添加了更多语句之后。

缩进的HEREDOC标记

另一种常见情况出现在HEREDOC或NOWDOC字符串中。如果前面有空格、制表符等,终止标记将被忽略:

print <<< END
    Content...
    Content....
  END;
# ↑ terminator isn't exactly at the line start

因此,解析器假定HEREDOC字符串将一直持续到文件的末尾(因此是“意外的$end”)。几乎所有的ide和语法高亮编辑器都会明确显示或发出警告。

转义的引号

如果你在字符串中使用\,它有一个特殊的含义。这称为“转义字符”,通常告诉解析器按字面意思取下一个字符。

示例:echo 'Jim said \'Hello\ ";将打印Jim说'hello'

如果转义字符串的结束引号,结束引号将被字面上理解,而不是像预期的那样,即作为字符串的一部分而不是结束字符串的可打印引号。这通常会在打开下一个字符串后或脚本结束时显示为解析错误。

在Windows中指定路径时非常常见的错误:“C:\xampp\htdocs\”是错误的。你需要“C:\\xampp\\htdocs\\ \”。另外,PHP通常会转换unix风格的路径(例如。“C:/xampp/htdocs/”)到Windows的正确路径。

替代语法

在模板中使用语句/代码块的替代语法时,很少会看到这种语法错误。使用if:和else:和一个缺失的endif;为例。

参见:

PHP语法错误“意外$end” 解析错误:语法错误,在我的PHP代码文件意外结束 解析错误语法错误文件意外结束,使用PHP PHP解析错误:语法错误,CodeIgniter视图中的文件意外结束 解析错误:语法错误,文件意外结束(注册脚本) “解析错误:语法错误,意外$end”为我的uni注册分配 修复PHP错误:PHP错误#3:文件意外结束

其他回答

意想不到的美元结束

当PHP谈到“意外的$end”时,这意味着您的代码在解析器期望更多代码时结束了。(如果从字面上理解,这个信息有点误导。它不是关于一个名为“$end”的变量,就像新来者有时认为的那样。它指的是“文件的结束”,EOF。)

原因:代码块/和函数或类声明的{和}不平衡。

它几乎总是缺少一个}花括号来关闭前面的代码块。它的意思是,解析器希望找到一个结束},但实际上到达了文件的末尾。

同样,使用适当的缩进来避免此类问题。 使用带有括号匹配的IDE,找出}错误的地方。 在大多数ide和文本编辑器中都有快捷键: NetBeans, PhpStorm, Komodo: Ctrl[和Ctrl] Eclipse, Aptana: CtrlShiftP Atom, Sublime: Ctrlm - Zend Studio Ctrlm Geany, notepad++: CtrlB - Joe: CtrlG - Emacs: C-M-n - Vim: %

大多数ide还突出显示匹配的大括号、方括号和圆括号。 这使得检查它们的相关性变得非常容易:

无端接的表达式

对于未结束的表达式或语句,也会出现意外的$end语法/解析器错误:

$var = func(1, ?>EOF

因此,首先查看脚本的末尾。拖尾;在任何PHP脚本中,最后一条语句通常是多余的。但你应该有一个。正是因为它缩小了这些语法问题的范围。特别是在您发现自己在脚本末尾添加了更多语句之后。

缩进的HEREDOC标记

另一种常见情况出现在HEREDOC或NOWDOC字符串中。如果前面有空格、制表符等,终止标记将被忽略:

print <<< END
    Content...
    Content....
  END;
# ↑ terminator isn't exactly at the line start

因此,解析器假定HEREDOC字符串将一直持续到文件的末尾(因此是“意外的$end”)。几乎所有的ide和语法高亮编辑器都会明确显示或发出警告。

转义的引号

如果你在字符串中使用\,它有一个特殊的含义。这称为“转义字符”,通常告诉解析器按字面意思取下一个字符。

示例:echo 'Jim said \'Hello\ ";将打印Jim说'hello'

如果转义字符串的结束引号,结束引号将被字面上理解,而不是像预期的那样,即作为字符串的一部分而不是结束字符串的可打印引号。这通常会在打开下一个字符串后或脚本结束时显示为解析错误。

在Windows中指定路径时非常常见的错误:“C:\xampp\htdocs\”是错误的。你需要“C:\\xampp\\htdocs\\ \”。另外,PHP通常会转换unix风格的路径(例如。“C:/xampp/htdocs/”)到Windows的正确路径。

替代语法

在模板中使用语句/代码块的替代语法时,很少会看到这种语法错误。使用if:和else:和一个缺失的endif;为例。

参见:

PHP语法错误“意外$end” 解析错误:语法错误,在我的PHP代码文件意外结束 解析错误语法错误文件意外结束,使用PHP PHP解析错误:语法错误,CodeIgniter视图中的文件意外结束 解析错误:语法错误,文件意外结束(注册脚本) “解析错误:语法错误,意外$end”为我的uni注册分配 修复PHP错误:PHP错误#3:文件意外结束

意想不到的“=”

这可能是由于在变量名中使用无效字符造成的。变量名称必须遵循以下规则:

变量名与PHP中的其他标签遵循相同的规则。有效变量名以字母或下划线开头,后面跟着任意数量的字母、数字或下划线。作为正则表达式,它可以这样表示:'[a- za - z_ \x7f-\xff][a- za - z0 -9_\x7f-\xff]*'

语法错误是什么?

PHP属于c风格的命令式编程语言。它有严格的语法规则,当遇到错位的符号或标识符时,它无法恢复。它无法猜测你的编码意图。

最重要的建议

这里有一些你总是可以采取的基本预防措施:

使用适当的代码缩进,或采用任何高级的编码风格。 可读性可以防止不规则性。 使用带有语法高亮显示功能的IDE或PHP编辑器。 这也有助于括号/方括号平衡。 阅读手册中的语言参考和示例。 两次,达到一定程度的熟练。

如何解释解析器错误

典型的语法错误消息如下:

解析错误:语法错误,意外的T_STRING,期望在file.php第217行有';

它列出了语法错误的可能位置。请参阅提到的文件名和行号。

像T_STRING这样的别名解释了解析器/标记器最终不能处理哪个符号。然而,这并不一定是语法错误的原因。

查看之前的代码行也很重要。通常语法错误只是之前发生的意外。错误行号只是解析器最终放弃处理的地方。

解决语法错误

有许多方法可以缩小和修复语法问题。

Open the mentioned source file. Look at the mentioned code line. For runaway strings and misplaced operators, this is usually where you find the culprit. Read the line left to right and imagine what each symbol does. More regularly you need to look at preceding lines as well. In particular, missing ; semicolons are missing at the previous line ends/statement. (At least from the stylistic viewpoint. ) If { code blocks } are incorrectly closed or nested, you may need to investigate even further up the source code. Use proper code indentation to simplify that. Look at the syntax colorization! Strings and variables and constants should all have different colors. Operators +-*/. should be tinted distinct as well. Else they might be in the wrong context. If you see string colorization extend too far or too short, then you have found an unescaped or missing closing " or ' string marker. Having two same-colored punctuation characters next to each other can also mean trouble. Usually, operators are lone if it's not ++, --, or parentheses following an operator. Two strings/identifiers directly following each other are incorrect in most contexts. Whitespace is your friend. Follow any coding style. Break up long lines temporarily. You can freely add newlines between operators or constants and strings. The parser will then concretize the line number for parsing errors. Instead of looking at the very lengthy code, you can isolate the missing or misplaced syntax symbol. Split up complex if statements into distinct or nested if conditions. Instead of lengthy math formulas or logic chains, use temporary variables to simplify the code. (More readable = fewer errors.) Add newlines between: The code you can easily identify as correct, The parts you're unsure about, And the lines which the parser complains about. Partitioning up long code blocks really helps to locate the origin of syntax errors. Comment out offending code. If you can't isolate the problem source, start to comment out (and thus temporarily remove) blocks of code. As soon as you got rid of the parsing error, you have found the problem source. Look more closely there. Sometimes you want to temporarily remove complete function/method blocks. (In case of unmatched curly braces and wrongly indented code.) When you can't resolve the syntax issue, try to rewrite the commented out sections from scratch. As a newcomer, avoid some of the confusing syntax constructs. The ternary ? : condition operator can compact code and is useful indeed. But it doesn't aid readability in all cases. Prefer plain if statements while unversed. PHP's alternative syntax (if:/elseif:/endif;) is common for templates, but arguably less easy to follow than normal { code } blocks. The most prevalent newcomer mistakes are: Missing semicolons ; for terminating statements/lines. Mismatched string quotes for " or ' and unescaped quotes within. Forgotten operators, in particular for the string . concatenation. Unbalanced ( parentheses ). Count them in the reported line. Are there an equal number of them? Don't forget that solving one syntax problem can uncover the next. If you make one issue go away, but other crops up in some code below, you're mostly on the right path. If after editing a new syntax error crops up in the same line, then your attempted change was possibly a failure. (Not always though.) Restore a backup of previously working code, if you can't fix it. Adopt a source code versioning system. You can always view a diff of the broken and last working version. Which might be enlightening as to what the syntax problem is. Invisible stray Unicode characters: In some cases, you need to use a hexeditor or different editor/viewer on your source. Some problems cannot be found just from looking at your code. Try grep --color -P -n "\[\x80-\xFF\]" file.php as the first measure to find non-ASCII symbols. In particular BOMs, zero-width spaces, or non-breaking spaces, and smart quotes regularly can find their way into the source code. Take care of which type of linebreaks are saved in files. PHP just honors \n newlines, not \r carriage returns. Which is occasionally an issue for MacOS users (even on OS  X for misconfigured editors). It often only surfaces as an issue when single-line // or # comments are used. Multiline /*...*/ comments do seldom disturb the parser when linebreaks get ignored. If your syntax error does not transmit over the web: It happens that you have a syntax error on your machine. But posting the very same file online does not exhibit it anymore. Which can only mean one of two things: You are looking at the wrong file! Or your code contained invisible stray Unicode (see above). You can easily find out: Just copy your code back from the web form into your text editor. Check your PHP version. Not all syntax constructs are available on every server. php -v for the command line interpreter <?php phpinfo(); for the one invoked through the webserver. Those aren't necessarily the same. In particular when working with frameworks, you will them to match up. Don't use PHP's reserved keywords as identifiers for functions/methods, classes or constants. Trial-and-error is your last resort.

如果所有这些都失败了,您总是可以谷歌您的错误消息。语法符号不那么容易搜索(Stack Overflow本身是由SymbolHound索引的)。因此,在你找到相关的东西之前,可能需要多看几页。

进一步指导:

PHP调试基础:David Sklar 修正PHP错误Jason McCreary PHP错误- Mario Lurig的10个常见错误 常见的PHP错误和解决方案 如何解决和修复你的WordPress网站 给设计师的PHP错误信息指南-粉碎杂志

白屏死机

如果你的网站是空白的,那么通常是语法错误造成的。 使用以下方法启用其显示:

error_reporting = E_ALL Display_errors = 1

在你的php.ini中,或者mod_php的。htaccess中, 甚至是带有FastCGI设置的。user.ini。

在破碎的脚本中启用它太晚了,因为PHP甚至不能解释/运行第一行。一个快速的解决方法是创建一个包装器脚本,比如test.php:

<?php
   error_reporting(E_ALL);
   ini_set("display_errors", 1);
   include("./broken-script.php");

然后通过访问这个包装器脚本调用失败的代码。

它还有助于启用PHP的error_log,并在脚本因HTTP 500响应而崩溃时查看web服务器的error.log。

意想不到的T_VARIABLE

一个“意外的T_VARIABLE”意味着有一个字面的$变量名,它不适合当前表达式/语句结构。

Missing semicolon It most commonly indicates a missing semicolon in the previous line. Variable assignments following a statement are a good indicator where to look: ⇓ func1() $var = 1 + 2; # parse error in line +2 String concatenation A frequent mishap are string concatenations with forgotten . operator: ⇓ print "Here comes the value: " $value; Btw, you should prefer string interpolation (basic variables in double quotes) whenever that helps readability. Which avoids these syntax issues. String interpolation is a scripting language core feature. No shame in utilizing it. Ignore any micro-optimization advise about variable . concatenation being faster. It's not. Missing expression operators Of course the same issue can arise in other expressions, for instance arithmetic operations: ⇓ print 4 + 7 $var; PHP can't guess here if the variable should have been added, subtracted or compared etc. Lists Same for syntax lists, like in array populations, where the parser also indicates an expected comma , for example: ⇓ $var = array("1" => $val, $val2, $val3 $val4); Or functions parameter lists: ⇓ function myfunc($param1, $param2 $param3, $param4) Equivalently do you see this with list or global statements, or when lacking a ; semicolon in a for loop. Class declarations This parser error also occurs in class declarations. You can only assign static constants, not expressions. Thus the parser complains about variables as assigned data: class xyz { ⇓ var $value = $_GET["input"]; Unmatched } closing curly braces can in particular lead here. If a method is terminated too early (use proper indentation!), then a stray variable is commonly misplaced into the class declaration body. Variables after identifiers You can also never have a variable follow an identifier directly: ⇓ $this->myFunc$VAR(); Btw, this is a common example where the intention was to use variable variables perhaps. In this case a variable property lookup with $this->{"myFunc$VAR"}(); for example. Take in mind that using variable variables should be the exception. Newcomers often try to use them too casually, even when arrays would be simpler and more appropriate. Missing parentheses after language constructs Hasty typing may lead to forgotten opening or closing parenthesis for if and for and foreach statements: ⇓ foreach $array as $key) { Solution: add the missing opening ( between statement and variable. ⇓ if ($var = pdo_query($sql) { $result = … The curly { brace does not open the code block, without closing the if expression with the ) closing parenthesis first. Else does not expect conditions ⇓ else ($var >= 0) Solution: Remove the conditions from else or use elseif. Need brackets for closure ⇓ function() use $var {} Solution: Add brackets around $var. Invisible whitespace As mentioned in the reference answer on "Invisible stray Unicode" (such as a non-breaking space), you might also see this error for unsuspecting code like: <?php ⇐ $var = new PDO(...); It's rather prevalent in the start of files and for copy-and-pasted code. Check with a hexeditor, if your code does not visually appear to contain a syntax issue.

另请参阅

搜索:意外T_VARIABLE

One more reason to occurrence of these errors is unexpected whitespace like similar characters with-in code, the code lines seems to be perfect, but they contains some specific characters which are similar to break line or whitespace or tab but they not get parsed by the parser. I face this issue when I try to put some code from webpage to the code editor by simply copy paste, I saw this error with array definition. everything was looking right in array definition. I can't sort out right error, finally I define this array in single line, then error was gone. then again I try to make that definition multiple like but manually adding break(Enter) for each array element and saved the file this time no parsing error by editor and also no error while running it. For Example I faced issue with this snippet which was on one blog, actually can't post those snippets ,cause stack overflow already knows the problem with code.

然后在解决它之后,我的工作片段是,它看起来类似于一个显示解析错误

语法错误,意外的“auth”(T_CONSTANT_ENCAPSED_STRING),期待']'

    public $aliases = [
        'csrf'=> \CodeIgniter\Filters\CSRF::class,
        'toolbar'=> \CodeIgniter\Filters\DebugToolbar::class,
        'honeypot'=> \CodeIgniter\Filters\Honeypot::class,
        'auth' => \App\Filters\Auth::class,
];