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

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版本中使用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'];

其他回答

意外的'endwhile' (T_ENDWHILE)

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

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

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

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

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

意想不到的(

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

语法错误是什么?

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。

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,
];

意想不到的“?”

如果您试图使用<?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();)。