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

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版本不兼容造成的,因此请根据平台设置检查供应商的要求。


当前回答

我认为这个话题讨论得太多了/太复杂了。使用IDE是完全避免任何语法错误的方法。我甚至会说,在没有IDE的情况下工作是不专业的。为什么?因为现代ide会在输入每个字符后检查语法。当您编写代码时,整行代码都变成红色,并且有一个很大的警告通知显示语法错误的确切类型和确切位置,那么绝对没有必要搜索其他解决方案。

使用语法检查IDE意味着:

您将(有效地)再也不会遇到语法错误,因为您在输入时就能看到它们。认真对待。

具有语法检查功能的优秀ide(它们都适用于Linux、Windows和Mac):

NetBeans(免费) PHPStorm [$199 USD] Eclipse与PHP插件[免费] Sublime [$80 USD](主要是一个文本编辑器,但可扩展的插件,如PHP语法分析器)

其他回答

意想不到的T_IF 意想不到的T_FOREACH 意想不到的T_FOR 意想不到的T_WHILE 意想不到的T_DO 意想不到的T_ECHO

控制结构,如if、foreach、for、while、list、global、return、do、print、echo只能作为语句使用。它们通常单独驻留在一行上。

Semicolon; where you at? Pretty universally have you missed a semicolon in the previous line if the parser complains about a control statement: ⇓ $x = myfunc() if (true) { Solution: look into the previous line; add semicolon. Class declarations Another location where this occurs is in class declarations. In the class section you can only list property initializations and method sections. No code may reside there. class xyz { if (true) {} foreach ($var) {} Such syntax errors commonly materialize for incorrectly nested { and }. In particular when function code blocks got closed too early. Statements in expression context Most language constructs can only be used as statements. They aren't meant to be placed inside other expressions: ⇓ $var = array(1, 2, foreach($else as $_), 5, 6); Likewise can't you use an if in strings, math expressions or elsewhere: ⇓ print "Oh, " . if (true) { "you!" } . " won't work"; // Use a ternary condition here instead, when versed enough. For embedding if-like conditions in an expression specifically, you often want to use a ?: ternary evaluation. The same applies to for, while, global, echo and a lesser extend list. ⇓ echo 123, echo 567, "huh?"; Whereas print() is a language built-in that may be used in expression context. (But rarely makes sense.) Reserved keywords as identifiers You also can't use do or if and other language constructs for user-defined functions or class names. (Perhaps in PHP 7. But even then it wouldn't be advisable.) Your have a semi-colon instead of a colon (:) or curly bracket ({) after your control block Control structures are typically wrapped in curly braces (but colons can be used in an alternative syntax) to represent their scope. If you accidentally use a semi-colon you prematurely close that block resulting in your closing statement throwing an error.

    foreach ($errors as $error); <-- should be : or {

意想不到的“=”

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

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

意想不到的(

开括号通常跟在if/foreach/for/array/list这样的语言结构之后,或者开始一个算术表达式。它们在“strings”后,previous(),单独的$和一些典型的声明上下文中都是语法错误的。

Function declaration parameters A rarer occurrence for this error is trying to use expressions as default function parameters. This is not supported, even in PHP7: function header_fallback($value, $expires = time() + 90000) { Parameters in a function declaration can only be literal values or constant expressions. Unlike for function invocations, where you can freely use whatever(1+something()*2), etc. Class property defaults Same thing for class member declarations, where only literal/constant values are allowed, not expressions: class xyz { ⇓ var $default = get_config("xyz_default"); Put such things in the constructor. See also Why don't PHP attributes allow functions? Again note that PHP 7 only allows var $xy = 1 + 2 +3; constant expressions there. JavaScript syntax in PHP Using JavaScript or jQuery syntax won't work in PHP for obvious reasons: <?php ⇓ print $(document).text(); When this happens, it usually indicates an unterminated preceding string; and literal <script> sections leaking into PHP code context. isset(()), empty, key, next, current Both isset() and empty() are language built-ins, not functions. They need to access a variable directly. If you inadvertently add a pair of parentheses too much, then you'd create an expression however: ⇓ if (isset(($_GET["id"]))) { The same applies to any language construct that requires implicit variable name access. These built-ins are part of the language grammar, therefore don't permit decorative extra parentheses. User-level functions that require a variable reference -but get an expression result passed- lead to runtime errors instead.

意想不到的)

Absent function parameter You cannot have stray commas last in a function call. PHP expects a value there and thusly complains about an early closing ) parenthesis. ⇓ callfunc(1, 2, ); A trailing comma is only allowed in array() or list() constructs. Unfinished expressions If you forget something in an arithmetic expression, then the parser gives up. Because how should it possibly interpret that: ⇓ $var = 2 * (1 + ); And if you forgot the closing ) even, then you'd get a complaint about the unexpected semicolon instead. Foreach as constant For forgotten variable $ prefixes in control statements you will see: ↓ ⇓ foreach ($array as wrong) { PHP here sometimes tells you it expected a :: instead. Because a class::$variable could have satisfied the expected $variable expression..

意想不到的{

花括号{和}括起代码块。关于它们的语法错误通常表示一些不正确的嵌套。

Unmatched subexpressions in an if Most commonly unbalanced ( and ) are the cause if the parser complains about the opening curly { appearing too early. A simple example: ⇓ if (($x == $y) && (2 == true) { Count your parentheses or use an IDE which helps with that. Also don't write code without any spaces. Readability counts. { and } in expression context You can't use curly braces in expressions. If you confuse parentheses and curlys, it won't comply to the language grammar: ⇓ $var = 5 * {7 + $x}; There are a few exceptions for identifier construction, such as local scope variable ${references}. Variable variables or curly var expressions This is pretty rare. But you might also get { and } parser complaints for complex variable expressions: ⇓ print "Hello {$world[2{]} !"; Though there's a higher likelihood for an unexpected } in such contexts.

意想不到的}

当出现“意外}”错误时,您多半过早地关闭了代码块。

Last statement in a code block It can happen for any unterminated expression. And if the last line in a function/code block lacks a trailing ; semicolon: function whatever() { doStuff() } ⇧ Here the parser can't tell if you perhaps still wanted to add + 25; to the function result or something else. Invalid block nesting / Forgotten { You'll sometimes see this parser error when a code block was } closed too early, or you forgot an opening { even: function doStuff() { if (true) ⇦ print "yes"; } } ⇧ In above snippet the if didn't have an opening { curly brace. Thus the closing } one below became redundant. And therefore the next closing }, which was intended for the function, was not associable to the original opening { curly brace. Such errors are even harder to find without proper code indentation. Use an IDE and bracket matching.

意料之外的,期待的

需要条件/声明标头和代码块的语言构造将触发此错误。

参数列表 例如,不允许错误声明没有参数列表的函数: ⇓ 函数whatever { } 控制语句条件 你也不能无条件地有一个如果。 ⇓ 如果{ } 这显然说不通。对于常见的疑点,for/foreach, while/do等等,也是如此。 如果您遇到了这种特殊的错误,您绝对应该查找一些手册示例。

对于VS Code的新手,如果你看到语法错误,检查你是否保存了文件。如果你有一个错误的语法,保存文件,然后在不保存的情况下修复语法,VS Code会继续显示错误。只有保存文件后,错误信息才会消失。

意想不到的(

现在,在过时的PHP版本中经常可以看到意外的[array括号]。短数组语法从PHP >= 5.4开始可用。旧的安装只支持array()。

$php53 = array(1, 2, 3);
$php54 = [1, 2, 3];
         ⇑

数组函数结果解引用同样不适用于旧的PHP版本:

$result = get_whatever()["key"];
                      ⇑

这个错误在PHP中意味着什么?-“语法错误,意外的\[”显示了最常见和实用的解决方案。

不过,最好还是升级PHP安装。对于共享网络托管计划,首先要研究是否可以使用SetHandler php5 56-fcgi来启用新的运行时。

参见:

对函数result→进行解引用的PHP语法,从PHP 5.4开始可能 PHP语法错误,意外的“[” 数组的简写:是否存在像{}或[]这样的文字语法? PHP 5.3.10 vs PHP 5.5.3语法错误 数组()和[]的区别 PHP数组语法解析错误

顺便说一下,如果你对老版本和慢版本的PHP很感兴趣的话,还有预处理器和PHP 5.4语法下转换器。

导致意外语法错误的其他原因

如果不是PHP版本不匹配,那么通常是一个简单的拼写错误或新手语法错误:

You can't use array property declarations/expressions in classes, not even in PHP 7. protected $var["x"] = "Nope"; ⇑ Confusing [ with opening curly braces { or parentheses ( is a common oversight. foreach [$a as $b) ⇑ Or even: function foobar[$a, $b, $c] { ⇑ Or trying to dereference constants (before PHP 5.6) as arrays: $var = const[123]; ⇑ At least PHP interprets that const as a constant name. If you meant to access an array variable (which is the typical cause here), then add the leading $ sigil - so it becomes a $varname. You are trying to use the global keyword on a member of an associative array. This is not valid syntax: global $var['key'];

结束方括号

这种情况比较少见,但是终止数组[括号]也会出现语法错误。

同样,与)括号或}大括号不匹配是常见的: 函数foobar($a, $b, $c] { ⇑ 或者试图结束一个没有数组的数组: $var = 2]; 这通常发生在多行和嵌套数组声明中。 $数组=[1,2,3],4(5、6 (7 [8][9 10]],11),12]],15); ⇑ 如果是,请使用IDE进行括号匹配以查找任何过早的]数组闭包。至少使用更多的空格和换行来缩小范围。