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

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属于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


意想不到的T_STRING

T_STRING有点用词不当。它不引用引用的“字符串”。这意味着遇到了原始标识符。这可以是空白的单词、剩余的CONSTANT或函数名、被遗忘的不带引号的字符串或任何纯文本。

Misquoted strings This syntax error is most common for misquoted string values however. Any unescaped and stray " or ' quote will form an invalid expression: ⇓ ⇓ echo "<a href="http://example.com">click here</a>"; Syntax highlighting will make such mistakes super obvious. It's important to remember to use backslashes for escaping \" double quotes, or \' single quotes - depending on which was used as string enclosure. For convenience you should prefer outer single quotes when outputting plain HTML with double quotes within. Use double quoted strings if you want to interpolate variables, but then watch out for escaping literal " double quotes. For lengthier output, prefer multiple echo/print lines instead of escaping in and out. Better yet consider a HEREDOC section. Another example is using PHP entry inside HTML code generated with PHP: $text = '<div>some text with <?php echo 'some php entry' ?></div>' This happens if $text is large with many lines and developer does not see the whole PHP variable value and focus on the piece of code forgetting about its source. Example is here See also What is the difference between single-quoted and double-quoted strings in PHP?. Unclosed strings If you miss a closing " then a syntax error typically materializes later. An unterminated string will often consume a bit of code until the next intended string value: ⇓ echo "Some text", $a_variable, "and some runaway string ; success("finished"); ⇯ It's not just literal T_STRINGs which the parser may protest then. Another frequent variation is an Unexpected '>' for unquoted literal HTML. Non-programming string quotes If you copy and paste code from a blog or website, you sometimes end up with invalid code. Typographic quotes aren't what PHP expects: $text = ’Something something..’ + ”these ain't quotes”; Typographic/smart quotes are Unicode symbols. PHP treats them as part of adjoining alphanumeric text. For example ”these is interpreted as a constant identifier. But any following text literal is then seen as a bareword/T_STRING by the parser. The missing semicolon; again If you have an unterminated expression in previous lines, then any following statement or language construct gets seen as raw identifier: ⇓ func1() function2(); PHP just can't know if you meant to run two functions after another, or if you meant to multiply their results, add them, compare them, or only run one || or the other. Short open tags and <?xml headers in PHP scripts This is rather uncommon. But if short_open_tags are enabled, then you can't begin your PHP scripts with an XML declaration: ⇓ <?xml version="1.0"?> PHP will see the <? and reclaim it for itself. It won't understand what the stray xml was meant for. It'll get interpreted as constant. But the version will be seen as another literal/constant. And since the parser can't make sense of two subsequent literals/values without an expression operator in between, that'll be a parser failure. Invisible Unicode characters A most hideous cause for syntax errors are Unicode symbols, such as the non-breaking space. PHP allows Unicode characters as identifier names. If you get a T_STRING parser complaint for wholly unsuspicious code like: <?php print 123; You need to break out another text editor. Or an hexeditor even. What looks like plain spaces and newlines here, may contain invisible constants. Java-based IDEs are sometimes oblivious to an UTF-8 BOM mangled within, zero-width spaces, paragraph separators, etc. Try to reedit everything, remove whitespace and add normal spaces back in. You can narrow it down with with adding redundant ; statement separators at each line start: <?php ;print 123; The extra ; semicolon here will convert the preceding invisible character into an undefined constant reference (expression as statement). Which in return makes PHP produce a helpful notice. The `$` sign missing in front of variable names Variables in PHP are represented by a dollar sign followed by the name of the variable. The dollar sign ($) is a sigil that marks the identifier as a name of a variable. Without this sigil, the identifier could be a language keyword or a constant. This is a common error when the PHP code was "translated" from code written in another language (C, Java, JavaScript, etc.). In such cases, a declaration of the variable type (when the original code was written in a language that uses typed variables) could also sneak out and produce this error. Escaped Quotation marks If you use \ in a string, it has a special meaning. This is called an "Escape Character" and normally tells the parser to take the next character literally. Example: echo 'Jim said \'Hello\''; will print Jim said 'hello' If you escape the closing quote of a string, the closing quote will be taken literally and not as intended, i.e. as a printable quote as part of the string and not close the string. This will show as a parse error commonly after you open the next string or at the end of the script. Very common error when specifiying paths in Windows: "C:\xampp\htdocs\" is wrong. You need "C:\\xampp\\htdocs\\". Typed properties You need PHP ≥7.4 to use property typing such as: public stdClass $obj;


意外的T_CONSTANT_ENCAPSED_STRING意外的t_encapsed_and_空白

T_CONSTANT_ENCAPSED_STRING和T_ENCAPSED_AND_WHITESPACE是指带引号的“字符串”字面量。

它们在不同的上下文中使用,但语法问题非常相似。t_encaged…警告出现在双引号的字符串上下文中,而T_CONSTANT…字符串经常在普通PHP表达式或语句中出错。

Incorrect variable interpolation And it comes up most frequently for incorrect PHP variable interpolation: ⇓ ⇓ echo "Here comes a $wrong['array'] access"; Quoting arrays keys is a must in PHP context. But in double quoted strings (or HEREDOCs) this is a mistake. The parser complains about the contained single quoted 'string', because it usually expects a literal identifier / key there. More precisely it's valid to use PHP2-style simple syntax within double quotes for array references: echo "This is only $valid[here] ..."; Nested arrays or deeper object references however require the complex curly string expression syntax: echo "Use {$array['as_usual']} with curly syntax."; If unsure, this is commonly safer to use. It's often even considered more readable. And better IDEs actually use distinct syntax colorization for that. Missing concatenation If a string follows an expression, but lacks a concatenation or other operator, then you'll see PHP complain about the string literal: ⇓ print "Hello " . WORLD " !"; While it's obvious to you and me, PHP just can't guess that the string was meant to be appended there. Confusing string quote enclosures The same syntax error occurs when confounding string delimiters. A string started by a single ' or double " quote also ends with the same. ⇓ print "<a href="' . $link . '">click here</a>"; ⌞⎽⎽⎽⎽⎽⎽⎽⎽⌟⌞⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⌟⌞⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⌟ That example started with double quotes. But double quotes were also destined for the HTML attributes. The intended concatenation operator within however became interpreted as part of a second string in single quotes. Tip: Set your editor/IDE to use slightly distinct colorization for single and double quoted strings. (It also helps with application logic to prefer e.g. double quoted strings for textual output, and single quoted strings only for constant-like values.) This is a good example where you shouldn't break out of double quotes in the first place. Instead just use proper \" escapes for the HTML attributes´ quotes: print "<a href=\"{$link}\">click here</a>"; While this can also lead to syntax confusion, all better IDEs/editors again help by colorizing the escaped quotes differently. Missing opening quote Equivalently are forgotten opening "/' quotes a recipe for parser errors: ⇓ make_url(login', 'open'); Here the ', ' would become a string literal after a bareword, when obviously login was meant to be a string parameter. Array lists If you miss a , comma in an array creation block, the parser will see two consecutive strings: array( ⇓ "key" => "value" "next" => "....", ); Note that the last line may always contain an extra comma, but overlooking one in between is unforgivable. Which is hard to discover without syntax highlighting. Function parameter lists The same thing for function calls: ⇓ myfunc(123, "text", "and" "more") Runaway strings A common variation are quite simply forgotten string terminators: ⇓ mysql_evil("SELECT * FROM stuffs); print "'ok'"; ⇑ Here PHP complains about two string literals directly following each other. But the real cause is the unclosed previous string of course. HEREDOC indentation Prior PHP 7.3, the heredoc string end delimiter can't be prefixed with spaces: print <<< HTML <link..> HTML; ⇑ Solution: upgrade PHP or find a better hoster.

另请参阅

PHP中关联数组的插值(双引号字符串) 语法错误,意外的T_CONSTANT_ENCAPSED_STRING 语法错误,PHP中意外的T_CONSTANT_ENCAPSED_STRING SQL查询中出现意外的T_CONSTANT_ENCAPSED_STRING错误


意想不到的(

开括号通常跟在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等等,也是如此。 如果您遇到了这种特殊的错误,您绝对应该查找一些手册示例。


意想不到的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 {

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

使用语法检查IDE意味着:

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

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

NetBeans(免费) PHPStorm [$199 USD] Eclipse与PHP插件[免费] Sublime [$80 USD](主要是一个文本编辑器,但可扩展的插件,如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版本中经常可以看到意外的[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进行括号匹配以查找任何过早的]数组闭包。至少使用更多的空格和换行来缩小范围。


意想不到的T_IS_EQUAL 意想不到的T_IS_GREATER_OR_EQUAL 意想不到的T_IS_IDENTICAL 意想不到的T_IS_NOT_EQUAL 意想不到的T_IS_NOT_IDENTICAL 意想不到的T_IS_SMALLER_OR_EQUAL 意想不到的< 意想不到的>

比较运算符,如==,>=,===,!=,<>,!==和<=或<和>,主要应该只在表达式中使用,例如if表达式。如果解析器抱怨它们,那么通常意味着它们周围的paren不正确或不匹配()。

Parens grouping In particular for if statements with multiple comparisons you must take care to correctly count opening and closing parenthesis: ⇓ if (($foo < 7) && $bar) > 5 || $baz < 9) { ... } ↑ Here the if condition here was already terminated by the ) Once your comparisons become sufficiently complex it often helps to split it up into multiple and nested if constructs rather. isset() mashed with comparing A common newcomer is pitfal is trying to combine isset() or empty() with comparisons: ⇓ if (empty($_POST["var"] == 1)) { Or even: ⇓ if (isset($variable !== "value")) { This doesn't make sense to PHP, because isset and empty are language constructs that only accept variable names. It doesn't make sense to compare the result either, because the output is only/already a boolean. Confusing >= greater-or-equal with => array operator Both operators look somewhat similar, so they sometimes get mixed up: ⇓ if ($var => 5) { ... } You only need to remember that this comparison operator is called "greater than or equal" to get it right. See also: If statement structure in PHP Nothing to compare against You also can't combine two comparisons if they pertain the same variable name: ⇓ if ($xyz > 5 and < 100) PHP can't deduce that you meant to compare the initial variable again. Expressions are usually paired according to operator precedence, so by the time the < is seen, there'd be only a boolean result left from the original variable. See also: unexpected T_IS_SMALLER_OR_EQUAL Comparison chains You can't compare against a variable with a row of operators: ⇓ $reult = (5 < $x < 10); This has to be broken up into two comparisons, each against $x. This is actually more a case of blacklisted expressions (due to equivalent operator associativity). It's syntactically valid in a few C-style languages, but PHP wouldn't interpret it as expected comparison chain either. Unexpected > Unexpected < The greater than > or less than < operators don't have a custom T_XXX tokenizer name. And while they can be misplaced like all they others, you more often see the parser complain about them for misquoted strings and mashed HTML: ⇓ print "<a href='z">Hello</a>"; ↑ This amounts to a string "<a href='z" being compared > to a literal constant Hello and then another < comparison. Or that's at least how PHP sees it. The actual cause and syntax mistake was the premature string " termination. It's also not possible to nest PHP start tags: <?php echo <?php my_func(); ?> ↑

参见:

php T_IS_NOT_EQUAL错误 语法错误,意外的T_IS_EQUAL 返回语句的语法错误 http://forums.phpfreaks.com/topic/96891-parse-error-syntax-error-unexpected-t-is-not-identical-expecting-or/


意想不到的T_IF 意想不到的T_ELSEIF 意想不到的T_ELSE 意想不到的T_ENDIF

条件控件块if、elseif和else遵循一个简单的结构。当你遇到语法错误时,很可能只是无效的块嵌套→缺少{花括号}——或者多了一个。

Missing { or } due to incorrect indentation Mismatched code braces are common to less well-formatted code such as: if((!($opt["uniQartz5.8"]!=$this->check58)) or (empty($_POST['poree']))) {if ($true) {echo"halp";} elseif((!$z)or%b){excSmthng(False,5.8)}elseif (False){ If your code looks like this, start afresh! Otherwise it's unfixable to you or anyone else. There's no point in showcasing this on the internet to inquire for help. You will only be able to fix it, if you can visually follow the nested structure and relation of if/else conditionals and their { code blocks }. Use your IDE to see if they're all paired. if (true) { if (false) { … } elseif ($whatever) { if ($something2) { … } else { … } } else { … } if (false) { // a second `if` tree … } else { … } } elseif (false) { … } Any double } } will not just close a branch, but a previous condition structure. Therefore stick with one coding style; don't mix and match in nested if/else trees. Apart from consistency here, it turns out helpful to avoid lengthy conditions too. Use temporary variables or functions to avoid unreadable if-expressions. IF cannot be used in expressions A surprisingly frequent newcomer mistake is trying to use an if statement in an expression, such as a print statement: ⇓ echo "<a href='" . if ($link == "example.org") { echo … Which is invalid of course. You can use a ternary conditional, but beware of readability impacts. echo "<a href='" . ($link ? "http://yes" : "http://no") . "</a>"; Otherwise break such output constructs up: use multiple ifs and echos. Better yet, use temporary variables, and place your conditionals before: if ($link) { $href = "yes"; } else { $href = "no"; } echo "<a href='$href'>Link</a>"; Defining functions or methods for such cases often makes sense too. Control blocks don't return "results" Now this is less common, but a few coders even try to treat if as if it could return a result: $var = if ($x == $y) { "true" }; Which is structurally identical to using if within a string concatenation / expression. But control structures (if / foreach / while) don't have a "result". The literal string "true" would also just be a void statement. You'll have to use an assignment in the code block: if ($x == $y) { $var = "true"; } Alternatively, resort to a ?: ternary comparison. If in If You cannot nest an if within a condition either: ⇓ if ($x == true and (if $y != false)) { ... } Which is obviously redundant, because the and (or or) already allows chaining comparisons. Forgotten ; semicolons Once more: Each control block needs to be a statement. If the previous code piece isn't terminated by a semicolon, then that's a guaranteed syntax error: ⇓ $var = 1 + 2 + 3 if (true) { … } Btw, the last line in a {…} code block needs a semicolon too. Semicolon too early Now it's probably wrong to blame a particular coding style, as this pitfall is too easy to overlook: ⇓ if ($x == 5); { $y = 7; } else ← { $x = -1; } Which happens more often than you might imagine. When you terminate the if () expression with ; it will execute a void statement. The ; becomes a an empty {} of its own! The {…} block thus is detached from the if, and would always run. So the else no longer had a relation to an open if construct, which is why this would lead to an Unexpected T_ELSE syntax error. Which also explains a likewise subtle variation of this syntax error: if ($x) { x_is_true(); }; else { something_else(); }; Where the ; after the code block {…} terminates the whole if construct, severing the else branch syntactically. Not using code blocks It's syntactically allowed to omit curly braces {…} for code blocks in if/elseif/else branches. Which sadly is a syntax style very common to unversed coders. (Under the false assumption this was quicker to type or read). However that's highly likely to trip up the syntax. Sooner or later additional statements will find their way into the if/else branches: if (true) $x = 5; elseif (false) $x = 6; $y = 7; ← else $z = 0; But to actually use code blocks, you do have to write {…} them as such! Even seasoned programmers avoid this braceless syntax, or at least understand it as an exceptional exception to the rule. Else / Elseif in wrong order One thing to remind yourself is the conditional order, of course. if ($a) { … } else { … } elseif ($b) { … } ↑ You can have as many elseifs as you want, but else has to go last. That's just how it is. Class declarations As mentioned above, you can't have control statements in a class declaration: class xyz { if (true) { function ($var) {} } You either forgot a function definition, or closed one } too early in such cases. Unexpected T_ELSEIF / T_ELSE When mixing PHP and HTML, the closing } for an if/elseif must be in the same PHP block <?php ?> as the next elseif/else. This will generate an error as the closing } for the if needs to be part of the elseif: <?php if ($x) { ?> html <?php } ?> <?php elseif ($y) { ?> html <?php } ?> The correct form <?php } elseif: <?php if ($x) { ?> html <?php } elseif ($y) { ?> html <?php } ?> This is more or less a variation of incorrect indentation - presumably often based on wrong coding intentions. You cannot mash other statements inbetween if and elseif/else structural tokens: if (true) { } echo "in between"; ← elseif (false) { } ?> text <?php ← else { } Either can only occur in {…} code blocks, not in between control structure tokens. This wouldn't make sense anyway. It's not like that there was some "undefined" state when PHP jumps between if and else branches. You'll have to make up your mind where print statements belong to / or if they need to be repeated in both branches. Nor can you part an if/else between different control structures: foreach ($array as $i) { if ($i) { … } } else { … } There is no syntactic relation between the if and else. The foreach lexical scope ends at }, so there's no point for the if structure to continue. T_ENDIF If an unexpected T_ENDIF is complained about, you're using the alternative syntax style if: ⋯ elseif: ⋯ else: ⋯ endif;. Which you should really think twice about. A common pitfall is confusing the eerily similar : colon for a ; semicolon. (Covered in "Semicolon too early") As indentation is harder to track in template files, the more when using the alternative syntax - it's plausible your endif; does not match any if:. Using } endif; is a doubled if-terminator. While an "unexpected $end" is usually the price for a forgotten closing } curly brace. Assignment vs. comparison So, this is not a syntax error, but worth mentioning in this context: ⇓ if ($x = true) { } else { do_false(); } That's not a ==/=== comparison, but an = assignment. This is rather subtle, and will easily lead some users to helplessly edit whole condition blocks. Watch out for unintended assignments first - whenver you experience a logic fault / misbeheviour.


意想不到的T_LNUMBER

令牌T_LNUMBER指向一个“长”/ number。

Invalid variable names In PHP, and most other programming languages, variables cannot start with a number. The first character must be alphabetic or an underscore. $1 // Bad $_1 // Good Quite often comes up for using preg_replace-placeholders "$1" in PHP context: # ↓ ⇓ ↓ preg_replace("/#(\w+)/e", strtopupper($1) ) Where the callback should have been quoted. (Now the /e regex flag has been deprecated. But it's sometimes still misused in preg_replace_callback functions.) The same identifier constraint applies to object properties, btw. ↓ $json->0->value While the tokenizer/parser does not allow a literal $1 as variable name, one could use ${1} or ${"1"}. Which is a syntactic workaround for non-standard identifiers. (It's best to think of it as a local scope lookup. But generally: prefer plain arrays for such cases!) Amusingly, but very much not recommended, PHPs parser allows Unicode-identifiers; such that $➊ would be valid. (Unlike a literal 1). Stray array entry An unexpected long can also occur for array declarations - when missing , commas: # ↓ ↓ $xy = array(1 2 3); Or likewise function calls and declarations, and other constructs: func(1, 2 3); function xy($z 2); for ($i=2 3<$z) So usually there's one of ; or , missing for separating lists or expressions. Misquoted HTML And again, misquoted strings are a frequent source of stray numbers: # ↓ ↓ echo "<td colspan="3">something bad</td>"; Such cases should be treated more or less like Unexpected T_STRING errors. Other identifiers Neither functions, classes, nor namespaces can be named beginning with a number either: ↓ function 123shop() { Pretty much the same as for variable names.


意想不到的“?”

如果您试图使用<?PHP <?PHP这个错误将被返回*。

$var = 'hello '<?php echo 'world'; ?>;

*为PHP版本4.3.1,4.3.5——4.3.11 4.4.0——4.1.1 5.0.0——5.0.5 10/24/11——4.4.9 5.1.0——5.1.6 5.2.0——5.2.17 5.3.0——5.3.29 5.4.0 5.4.45,发送,5.5.38 5.6.0——5.6.40 7.0.0——7.0.33 7.1.0——7.1.33 7.2.0——7.2.34 7.3.0——7.3.31 7.4.0——7.4.24


如果您正在尝试使用空合并操作符??在php7之前的版本中,你会得到这个错误。

<?= $a ?? 2; // works in PHP 7+
<?= (!empty($a)) ? $a : 2; // All versions of PHP

意想不到的”?,期望变量

可空类型也会出现类似的错误,如下所示:

function add(?int $sum): ?int {

这再次表明使用了过时的PHP版本(CLI版本PHP -v或web服务器绑定的phpinfo();)。


意外的'continue' (T_CONTINUE)

Continue是一个语句(如for或if),必须单独显示。它不能用作表达式的一部分。部分原因是continue不返回值,但在表达式中,每个子表达式都必须产生某个值,因此整个表达式都会产生一个值。这就是语句和表达式的区别。

这意味着continue不能用于三元语句或任何需要返回值的语句。

意外的“中断”(T_BREAK)

休息也是一样;当然可以。它也不能用于表达式上下文,而是一个严格语句(与foreach或if块处于同一级别)。

意外的“返回”(T_RETURN)

对于return来说,这可能更令人惊讶,但这也只是一个块级语句。它确实向更高的作用域/函数返回一个值(或NULL),但它不作为表达式本身计算。→也就是说:return(return(false);;


意想不到的“=”

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

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


意外的'endwhile' (T_ENDWHILE)

语法使用冒号-如果没有冒号,就会发生上述错误。

<?php while($query->fetch()): ?>
 ....
<?php endwhile; ?>

这种语法的替代方法是使用花括号:

<?php while($query->fetch()) { ?>
  ....
<?php } ?>

http://php.net/manual/en/control-structures.while.php


意想不到的“。”

如果您试图在不受支持的PHP版本中使用splat操作符(…),就会发生这种情况。

... 首次在PHP 5.6中可用来捕获函数的可变数量的参数:

function concatenate($transform, ...$strings) {
    $string = '';
    foreach($strings as $piece) {
        $string .= $piece;
    }
    return($transform($string));
}

echo concatenate("strtoupper", "I'd ", "like ", 4 + 2, " apples");
// This would print:
// I'D LIKE 6 APPLES

在PHP 7.4中,可以将它用于Array表达式。

$parts = ['apple', 'pear'];
$fruits = ['banana', 'orange', ...$parts, 'watermelon'];
// ['banana', 'orange', 'apple', 'pear', 'watermelon'];

意想不到的:

1. PHP 8命名参数语法

Unexpected ':', expected ',' or ')'

如果试图在PHP < 8的版本中使用PHP 8的新命名形参功能,将会出现以下错误:

$table->string(column:'Name');

解决方案:

将PHP版本升级到PHP 8.0.0或更高版本 不要使用命名参数(按照预期的顺序传递参数)

2. 裁剪类::分隔符

以“解析错误:语法错误,意外的‘:’”开头的错误消息可能是由于错误地将类静态引用class::$Variable写成class:$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,
];

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