Everyone runs into syntax errors. Even experienced programmers make typos. For newcomers, it's just part of the learning process. However, it's often easy to interpret error messages such as:
PHP Parse error: syntax error, unexpected '{' in index.php on line 20
The unexpected symbol isn't always the real culprit. But the line number gives a rough idea of where to start looking.
Always look at the code context. The syntax mistake often hides in the mentioned or in previous code lines. Compare your code against syntax examples from the manual.
While not every case matches the other. Yet there are some general steps to solve syntax mistakes. This references summarized the common pitfalls:
Unexpected T_CONSTANT_ENCAPSED_STRING
Unexpected T_ENCAPSED_AND_WHITESPACE
Unexpected continue (T_CONTINUE)
Unexpected continue (T_BREAK)
Unexpected continue (T_RETURN)
Unexpected ,
(comma)
Unpexected .
(period)
Unexpected ;
(semicolon)
Unexpected *
(asterisk)
Unexpected :
(colon)
Unexpected &
(call-time pass-by-reference)
Closely related references:
和:
尽管 Stack Overflow 也欢迎新手程序员,但它主要针对专业编程问题。
如果您的浏览器显示诸如 “SyntaxError:非法字符” 之类的错误消息,则它实际上不是与php相关的,而是javascript-语法错误。
供应商代码上出现的语法错误:最后,请考虑如果语法错误不是由于编辑代码库而引起的,而是在外部供应商软件包安装或升级后出现的,则可能是由于 PHP 版本不兼容所致,因此请针对您的平台检查供应商的要求设置。
PHP 属于C 风格和命令式编程语言。它具有严格的语法规则,遇到错位的符号或标识符时无法恢复。它无法猜测您的编码意图。
您可以始终采取一些基本的预防措施:
典型的语法错误消息显示为:
解析错误:语法错误,意外的T_STRING ,期待'
;
'中的线217 file.php
其中列出了语法错误的可能位置。请参阅提到的文件名和行号。
诸如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:
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.
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.
If all else fails, you can always google your error message. Syntax symbols aren't as easy to search for (Stack Overflow itself is indexed by SymbolHound though). Therefore it may take looking through a few more pages before you find something relevant.
Further guides:
If your website is just blank, then typically a syntax error is the cause. Enable their display with:
error_reporting = E_ALL
display_errors = 1
In your php.ini
generally, or via .htaccess
for mod_php,
or even .user.ini
with FastCGI setups.
在损坏的脚本中启用它为时已晚,因为 PHP 甚至无法解释 / 运行第一行。一个快速的解决方法是设计一个包装脚本,例如test.php
:
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
include("./broken-script.php");
然后通过访问此包装器脚本来调用失败的代码。
当脚本因 HTTP 500 响应而崩溃时,它还有助于启用 PHP 的error_log
并查看Web 服务器的error.log
我认为这个话题太过讨论 / 太复杂了。使用 IDE 是完全避免任何语法错误的方法。我什至会说没有 IDE 的工作是不专业的。为什么?因为现代的 IDE 会在您键入的每个字符之后检查语法。当您编码并且整个行变成红色,并且大的警告通知显示出语法错误的确切类型和确切位置时,那么就完全不需要搜索其他解决方案了。
您(有效)永远不会再遇到语法错误,仅因为您在键入时就可以正确看到它们。严重地。
具有语法检查功能的出色 IDE(它们都可用于 Linux,Windows 和 Mac):
[
如今,在过时的 PHP 版本中经常会出现[
从 PHP > = 5.4 开始,可以使用短数组语法。较旧的安装仅支持array()
。
$php53 = array(1, 2, 3);
$php54 = [1, 2, 3];
⇑
数组函数结果解引用同样不适用于旧版本的 PHP:
$result = get_whatever()["key"];
⇑
参考 - 此错误在 PHP 中意味着什么? -“语法错误,意外的\[
”显示了最常见和实际的解决方法。
但是,始终最好升级 PHP 安装。对于共享的虚拟主机计划,请首先研究是否SetHandler php56-fcgi
来启用较新的运行时。
也可以看看:
顺便说一句,如果您确实对较旧的 + 较慢的 PHP 版本非常了解,那么还可以使用预处理器和PHP 5.4 语法下变频器。
意外的其他原因[
语法错误
如果不是 PHP 版本不匹配,则通常是普通的错字或新手语法错误:
您不能在类中使用数组属性声明 / 表达式,甚至在 PHP 7 中也不能使用。
protected $var["x"] = "Nope";
⇑
[
与花括号{
或括号(
混淆)是常见的疏忽大意。
foreach [$a as $b)
⇑
甚至:
function foobar[$a, $b, $c] {
⇑
或尝试取消引用常量(在 PHP 5.6 之前)作为数组:
$var = const[123];
⇑
至少 PHP 将该const
解释为常量名称。
如果要访问数组变量(这是此处的典型原因),请添加前导$
sigil - 使其变为$varname
。
您正在尝试在关联数组的成员上global
这是无效的语法:
global $var['key'];
]
右方括号这种情况比较少见,但是使用终止数组]
括号也会发生语法错误。
同样, )
括号或}
花括号不匹配是很常见的:
function foobar($a, $b, $c] {
⇑
或尝试在没有数组的地方结束数组:
$var = 2];
这通常发生在多行和嵌套数组声明中。
$array = [1,[2,3],4,[5,6[7,[8],[9,10]],11],12]],15];
⇑
如果是这样,请使用 IDE 进行括号匹配,以查找任何过早的 [ ]
数组闭包。至少要使用更大的间距和换行符来缩小范围。