语法错误是什么?
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。