PHP 解析/语法错误;以及如何解决它们
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18050071/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP parse/syntax errors; and how to solve them
提问by mario
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
PHP 解析错误:语法错误,第 20 行 index.php 中出现意外的“{”
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 orin 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_WHITESPACEUnexpected 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)
意外的T_IF
意外的T_FOREACH
意外的T_FOR
意外的T_WHILE
意外的T_DO
意外的T_PRINT
意外的T_ECHO意外的“公共”(T_PUBLIC)
意外的“私有”(T_PRIVATE)
意外的“受保护”(T_PROTECTED)
意外的“最终”(T_FINAL)……意外的 T_CLASS...
意外
,
(逗号)意外
.
(期间)意外
;
(分号)意外
*
(星号)意外
:
(冒号)意外
&
(调用时传递引用)
Closely related references:
密切相关的参考资料:
- What does this error mean in PHP? (runtime errors)
- What does this symbol mean in PHP? (language tokens)
- Those
“”
smart‘'
quotes mean nothing to PHP
And:
和:
- The PHP manual on php.netand its various language tokens
- Or Wikipedia's syntax introduction on PHP.
- And lastly our phptag-wikiof course.
While Stack Overflow is also welcoming rookie coders, it's mostly targetted at professional programming questions.
虽然 Stack Overflow 也欢迎新手程序员,但它主要针对专业编程问题。
- Answering everyone's coding mistakes and narrow typos is considered mostly off-topic.
- So please take the time to follow the basic steps, before posting syntax fixing requests.
- If you still have to, please show your own solving initiative, attempted fixes, and your thought process on what looks or might be wrong.
- 回答每个人的编码错误和狭隘的错别字被认为主要是题外话。
- 因此,在发布语法修复请求之前,请花时间遵循基本步骤。
- 如果您仍然需要,请展示您自己的解决方案、尝试的修复以及您对看起来或可能出错的思考过程。
If your browserdisplays error messages such as "SyntaxError: illegal character", then it's not actually php-related, but a javascript-syntax error.
如果您的浏览器显示错误信息,如“语法错误:非法字符”,那就不是真正的PHP-相关,但JavaScript的-语法错误。
Syntax errors raised on vendor code:Finally, consider that if the syntax error was not raised by editing your codebase, but after an external vendor package install or upgrade, it could be due to PHP version incompatibility, so check the vendor's requirements against your platform setup.
供应商代码上引发的语法错误:最后,请考虑如果语法错误不是通过编辑代码库引发的,而是在外部供应商包安装或升级后引发的,可能是由于 PHP 版本不兼容,因此请根据您的平台检查供应商的要求设置。
采纳答案by mario
What are the syntax errors?
什么是语法错误?
PHP belongs to the C-styleand imperativeprogramming languages. It has rigid grammar rules, which it cannot recover from when encountering misplaced symbols or identifiers. It can't guess your coding intentions.
PHP 属于C 风格和命令式编程语言。它有严格的语法规则,遇到错位的符号或标识符时无法恢复。它无法猜测您的编码意图。
Most important tips
最重要的提示
There are a few basic precautions you can always take:
您可以随时采取一些基本的预防措施:
Use proper code indentation, or adopt any lofty coding style. Readability prevents irregularities.
Use an IDEor editor for PHPwith syntax highlighting. Which also help with parentheses/bracket balancing.
Read the language referenceand examples in the manual. Twice, to become somewhat proficient.
How to interpret parser errors
如何解释解析器错误
A typical syntax error message reads:
典型的语法错误消息如下:
Parse error: syntax error, unexpected T_STRING, expecting '
;
'in file.phpon line217
解析错误:语法错误,意想不到的T_STRING,期待“
;
”在file.php上线217
Which lists the possiblelocation of a syntax mistake. See the mentioned file nameand line number.
其中列出了语法错误的可能位置。请参阅提到的文件名和行号。
A monikersuch as T_STRING
explains which symbol the parser/tokenizer couldn't process finally. This isn't necessarily the cause of the syntax mistake, however.
一个绰号,如T_STRING
解释了符号解析器/标记生成器无法处理最后。然而,这不一定是语法错误的原因。
It's important to look into previous code linesas well. Often syntax errors are just mishaps that happened earlier. The error line number is just where the parser conclusively gave up to process it all.
查看以前的代码行也很重要。通常语法错误只是之前发生的不幸。错误行号正是解析器最终放弃处理它的地方。
Solving syntax errors
解决语法错误
There are many approaches to narrow down and fix syntax hiccups.
有很多方法可以缩小和修复语法问题。
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 linesas 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 indentationto 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 anycoding style.
Break up long lines temporarily.
You can freely add newlinesbetween 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 nestedif
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 reallyhelps to locate the origin of syntax errors.
Comment outoffending 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 rewritethe 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 plainif
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.
- Adopt a source code versioning system. You can always view a
Invisible stray Unicode characters: In some cases, you need to use a hexeditoror 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 linebreaksare saved in files.
PHP just honors \nnewlines, not \rcarriage 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 keywordsas identifiers for functions/methods, classes or constants.
Trial-and-error is your last resort.
打开提到的源文件。查看提到的代码行。
对于失控的字符串和错位的运算符,这通常是您找到罪魁祸首的地方。
从左到右阅读这行并想象每个符号的作用。
更经常地,您还需要查看前面的行。
特别是,
;
前一行结尾/语句中缺少缺少的分号。(至少从文体的角度来看。)如果
{
代码块}
被错误地关闭或嵌套,您可能需要进一步调查源代码。使用适当的代码缩进来简化它。
看看语法着色!
字符串、变量和常量都应该有不同的颜色。
操作员也
+-*/.
应该着色不同。否则他们可能处于错误的上下文中。如果您看到字符串着色延伸得太远或太短,那么您发现了未转义或丢失的结束标记
"
或'
字符串标记。两个相同颜色的标点符号相邻也意味着麻烦。通常情况下,运营商是唯一的,如果它不是
++
,--
或小括号操作如下。在大多数情况下,紧随其后的两个字符串/标识符是不正确的。
空白是你的朋友。遵循任何编码风格。
暂时打破长队。
您可以在运算符或常量和字符串之间自由添加换行符。然后解析器将具体化解析错误的行号。您可以隔离丢失或错位的语法符号,而不是查看非常冗长的代码。
将复杂的
if
语句拆分为不同的或嵌套的if
条件。使用临时变量来简化代码,而不是冗长的数学公式或逻辑链。(更具可读性 = 更少的错误。)
在以下之间添加换行符:
- 您可以轻松识别为正确的代码,
- 你不确定的部分,
- 以及解析器抱怨的行。
对长代码块进行分区确实有助于定位语法错误的来源。
注释掉违规代码。
如果您无法隔离问题源,请开始注释(从而暂时删除)代码块。
一旦你摆脱了解析错误,你就找到了问题的根源。仔细看看那里。
有时您想暂时删除完整的函数/方法块。(在不匹配的大括号和错误缩进的代码的情况下。)
当您无法解决语法问题时,请尝试从头开始重写注释掉的部分。
作为新手,请避免一些令人困惑的语法结构。
三元
? :
条件运算符可以压缩代码并且确实很有用。但它并不在所有情况下都有助于可读性。if
在不了解的情况下更喜欢简单的陈述。PHP的替代语法(
if:
/elseif:
/endif;
)是常见的模板,但可以说是不容易跟随比正常的{
代码}
块。
最常见的新手错误是:
缺少
;
用于终止语句/行的分号。不匹配的字符串引号
"
或'
其中的未转义引号。被遗忘的运算符,尤其是字符串
.
连接。不平衡的
(
括号)
。在报告的行中计算它们。它们的数量是否相等?
不要忘记解决一个语法问题可以发现下一个。
如果您解决了一个问题,但在下面的某些代码中又出现了其他问题,那么您基本上是在正确的道路上。
如果在编辑后在同一行中出现新的语法错误,那么您尝试的更改可能是失败的。(但并非总是如此。)
如果无法修复,请恢复以前工作代码的备份。
- 采用源代码版本控制系统。您始终可以查看
diff
损坏的和上次工作的版本。这可能对语法问题有启发意义。
- 采用源代码版本控制系统。您始终可以查看
不可见的杂散 Unicode 字符:在某些情况下,您需要在源代码上使用十六进制编辑器或不同的编辑器/查看器。有些问题不能仅仅通过查看您的代码来发现。
尝试
grep --color -P -n "\[\x80-\xFF\]" file.php
作为查找非 ASCII 符号的第一个措施。特别是 BOM、零宽度空格或不间断空格和智能引号可以定期进入源代码。
注意保存在文件中的换行符类型。
PHP 只尊重\n换行符,而不是\r回车。
对于 MacOS 用户来说,这偶尔会是一个问题(即使在 OS X 上,对于错误配置的编辑器)。
当使用单行
//
或#
注释时,它通常仅作为问题出现。/*...*/
当换行符被忽略时,多行注释很少会干扰解析器。
如果您的语法错误没有通过网络传输:您的机器上发生了语法错误。但是在线发布完全相同的文件不再显示它。这只能意味着两件事之一:
您正在查看错误的文件!
或者您的代码包含不可见的杂散 Unicode(见上文)。您可以轻松找到:只需将您的代码从 Web 表单复制回文本编辑器即可。
检查您的PHP 版本。并非所有的语法结构在每台服务器上都可用。
php -v
对于命令行解释器<?php phpinfo();
对于通过网络服务器调用的那个。
这些不一定相同。特别是在使用框架时,您会将它们匹配。不要使用PHP 的保留关键字作为函数/方法、类或常量的标识符。
反复试验是您的最后手段。
If all else fails, you can always googleyour error message. Syntax symbols aren't as easy to search for (Stack Overflow itself is indexed by SymbolHoundthough). Therefore it may take looking through a few more pages before you find something relevant.
如果所有其他方法都失败了,您可以随时在google 上搜索您的错误消息。语法符号不是那么容易搜索(尽管Stack Overflow 本身是由SymbolHound索引的)。因此,您可能需要多浏览几页才能找到相关内容。
Further guides:
更多指南:
- PHP Debugging Basicsby David Sklar
- Fixing PHP Errorsby Jason McCreary
- PHP Errors – 10 Common Mistakesby Mario Lurig
- Common PHP Errors and Solutions
- How to Troubleshoot and Fix your WordPress Website
- A Guide To PHP Error Messages For Designers- Smashing Magazine
- David Sklar 的PHP 调试基础
- 修复 PHP 错误by Jason McCreary
- PHP 错误 –Mario Lurig 的10 个常见错误
- 常见的 PHP 错误和解决方案
- 如何对您的 WordPress 网站进行故障排除和修复
- 给设计师的 PHP 错误信息指南- Smashing Magazine
White screen of death
白屏死机
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
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.ini
一般情况下,或通过.htaccess
mod_php,甚至.user.ini
使用 FastCGI 设置。
Enabling it within the broken script is too late because PHP can't even interpret/run the first line. A quick workaround is crafting a wrapper script, say test.php
:
在损坏的脚本中启用它为时已晚,因为 PHP 甚至无法解释/运行第一行。一个快速的解决方法是制作一个包装脚本,比如test.php
:
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
include("./broken-script.php");
Then invoke the failing code by accessing this wrapper script.
然后通过访问此包装器脚本调用失败的代码。
It also helps to enable PHP's error_log
and look into your webserver's error.log
when a script crashes with HTTP 500 responses.
当脚本因 HTTP 500 响应而崩溃时,它还有助于启用 PHPerror_log
并查看您的网络服务器error.log
。
回答by Sliq
I think this topic is totally overdiscussed/overcomplicated. Using an IDE is THE way to go to completely avoid any syntax errors. I would even say that working without an IDE is kind of unprofessional. Why? Because modern IDEs check your syntax after every character you type. When you code and your entire line turns red, and a big warning notice shows you the exact type and the exact position of the syntax error, then there's absolutely no need to search for another solution.
我认为这个话题完全被过度讨论/过于复杂。使用 IDE 是完全避免任何语法错误的方法。我什至会说在没有 IDE 的情况下工作有点不专业。为什么?因为现代 IDE 会在您键入每个字符后检查您的语法。当您编码并且您的整行变为红色,并且一个大警告通知显示您语法错误的确切类型和确切位置时,那么绝对没有必要寻找其他解决方案。
Using a syntax-checking IDE means:
使用语法检查 IDE 意味着:
You'll (effectively) never run into syntax errors again, simply because you see them right as you type. Seriously.
您将(有效地)永远不会再次遇到语法错误,仅仅因为您在键入时看到了它们。严重地。
Excellent IDEs with syntax check (all of them are available for Linux, Windows and Mac):
具有语法检查功能的优秀 IDE(所有这些都可用于 Linux、Windows 和 Mac):
- NetBeans[free]
- PHPStorm[$199 USD]
- Eclipsewith PHP Plugin[free]
- Sublime[$80 USD] (mainly a text editor, but expandable with plugins, like PHP Syntax Parser)
回答by mario
Unexpected [
意外 [
These days, the unexpected [
array bracket is commonly seen on outdated PHP versions. The short array syntaxis available since PHP >= 5.4. Older installations only support array()
.
如今,[
在过时的 PHP 版本上经常会看到意外的数组括号。的短数组语法可自PHP > = 5.4。较旧的安装仅支持array()
.
$php53 = array(1, 2, 3);
$php54 = [1, 2, 3];
?
Array function result dereferencing is likewise not available for older PHP versions:
数组函数结果解引用同样不适用于较旧的 PHP 版本:
$result = get_whatever()["key"];
?
Reference - What does this error mean in PHP? - "Syntax error, unexpected \[
"shows the most common and practical workarounds.
参考 - 这个错误在 PHP 中意味着什么?- “语法错误,意外\[
”显示了最常见和实用的解决方法。
Though, you're always better off just upgrading your PHP installation. For shared webhosting plans, first research if e.g. SetHandler php56-fcgi
can be used to enable a newer runtime.
不过,您最好只升级您的 PHP 安装。对于共享虚拟主机计划,首先研究是否SetHandler php56-fcgi
可以使用例如来启用更新的运行时。
See also:
也可以看看:
- PHP syntax for dereferencing function result → possible as of PHP 5.4
- PHP syntax error, unexpected '['
- Shorthand for arrays: is there a literal syntax like {} or []?
- PHP 5.3.10 vs PHP 5.5.3 syntax error unexpected '['
- PHP Difference between array() and []
- PHP Array Syntax Parse Error Left Square Bracket "["
- 用于取消引用函数结果的 PHP 语法 → PHP 5.4 起可能
- PHP 语法错误,意外的 '['
- 数组的简写:是否有像 {} 或 [] 这样的文字语法?
- PHP 5.3.10 vs PHP 5.5.3 语法错误意外的“[”
- PHP array() 和 [] 之间的区别
- PHP数组语法解析错误左方括号“[”
BTW, there are also preprocessors and PHP 5.4 syntax down-convertersif you're really clingy with older + slower PHP versions.
顺便说一句,如果您真的很喜欢旧的 + 较慢的 PHP 版本,那么还有预处理器和PHP 5.4 语法下转换器。
Other causes for Unexpected [
syntax errors
意外[
语法错误的其他原因
If it's not the PHP version mismatch, then it's oftentimes a plain typo or newcomer syntax mistake:
如果不是 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'];
您不能在 classes 中使用数组属性声明/表达式,甚至在 PHP 7 中也不能。
protected $var["x"] = "Nope"; ?
[
与左花括号{
或圆括号混淆(
是一个常见的疏忽。foreach [$a as $b) ?
甚至:
function foobar[$a, $b, $c] { ?
或者尝试将常量(PHP 5.6 之前)解引用为数组:
$var = const[123]; ?
至少 PHP 将其解释
const
为常量名称。如果您打算访问一个数组变量(这是这里的典型原因),那么添加前导
$
符 - 所以它变成了一个$varname
.您正在尝试
global
在关联数组的成员上使用关键字。这是无效的语法:global $var['key'];
Unexpected ]
closingsquare bracket
意外的]
结束方括号
This is somewhat rarer, but there are also syntax accidents with the terminating array ]
bracket.
这种情况比较少见,但也存在终止数组]
括号的语法错误。
Again mismatches with
)
parentheses or}
curly braces are common:function foobar($a, $b, $c] { ?
Or trying to end an array where there isn't one:
$var = 2];
Which often occurs in multi-lineand nestedarray declarations.
$array = [1,[2,3],4,[5,6[7,[8],[9,10]],11],12]],15]; ?
If so, use your IDE for bracket matching to find any premature
]
array closure. At the very least use more spacing and newlines to narrow it down.
与
)
括号或}
花括号不匹配的情况也很常见:function foobar($a, $b, $c] { ?
或者试图结束一个没有数组的数组:
$var = 2];
这通常发生在多行和嵌套数组声明中。
$array = [1,[2,3],4,[5,6[7,[8],[9,10]],11],12]],15]; ?
如果是这样,请使用您的 IDE 进行括号匹配以查找任何过早的
]
数组关闭。至少使用更多的间距和换行符来缩小它的范围。
回答by mario
Unexpected T_VARIABLE
意外的 T_VARIABLE
An "unexpected T_VARIABLE
" means that there's a literal $variable
name, which doesn't fit into the current expression/statement structure.
“意外T_VARIABLE
”意味着有一个字面$variable
名称,它不适合当前的表达式/语句结构。
Missing semicolon
It most commonly indicates a missing semicolonin 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 concatenationswith 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 languagecore 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 guesshere 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
orglobal
statements, or when lacking a;
semicolon in afor
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 identifierdirectly:
? $this->myFunc$VAR();
Btw, this is a common example where the intention was to use variable variablesperhaps. 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
andfor
andforeach
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 theif
expression with the)
closing parenthesis first.Else does not expect conditions
? else ($var >= 0)
Solution: Remove the conditions from
else
or useelseif
.Need brackets for closure
? function() uses $var {}
Solution: Add brackets around
$var
.Invisible whitespace
As mentioned in the reference answeron "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.
缺少分号
它最常表示前一行中缺少分号。语句后面的变量赋值是一个很好的指标:
? func1() $var = 1 + 2; # parse error in line +2
字符串连接
一个经常发生的事故是带有遗忘运算符的字符串连接
.
:? print "Here comes the value: " $value;
顺便说一句,只要有助于可读性,您应该更喜欢字符串插值(双引号中的基本变量)。这避免了这些语法问题。
字符串插值是脚本语言的核心功能。使用它并不可耻。忽略任何关于变量
.
连接更快的微优化建议。它不是。缺少表达式运算符
当然,在其他表达式中也会出现同样的问题,例如算术运算:
? print 4 + 7 $var;
PHP 无法在这里猜测变量是否应该被添加、减去或比较等。
列表
语法列表也是如此,就像在数组填充中一样,解析器还指示预期的逗号
,
,例如:? $var = array("1" => $val, $val2, $val3 $val4);
或函数参数列表:
? function myfunc($param1, $param2 $param3, $param4)
等效地,您是否会在
list
orglobal
语句中或;
在for
循环中缺少分号时看到这一点。类声明
这个解析器错误也发生在类声明中。您只能分配静态常量,不能分配表达式。因此解析器抱怨变量作为分配的数据:
class xyz { ? var $value = $_GET["input"];
无与伦比的
}
大括号在这里尤其可以引导。如果一个方法过早终止(使用适当的缩进!),那么一个杂散变量通常会被错误地放入类声明体中。标识符后的变量
? $this->myFunc$VAR();
顺便说一句,这是一个常见的例子,其中的意图可能是使用可变变量。在这种情况下
$this->{"myFunc$VAR"}();
,例如使用变量属性查找。请记住,使用可变变量应该是例外。新手经常尝试过于随意地使用它们,即使数组更简单更合适。
语言结构后缺少括号
冬冬打字可能导致被遗忘的左或右括号的
if
和for
和foreach
语句:? foreach $array as $key) {
解决方案:
(
在语句和变量之间添加缺少的开口。? if ($var = pdo_query($sql) { $result = …
大
{
括号不会打开代码块,没有先if
用)
右括号关闭表达式。否则不期望条件
? else ($var >= 0)
解决方案:从 中删除条件
else
或使用elseif
.需要括号来关闭
? function() uses $var {}
解决方案:在 周围添加括号
$var
。看不见的空白
正如在“Invisible Stray Unicode”(例如不间断空格)的参考答案中提到的,对于毫无戒心的代码,您可能还会看到此错误,例如:
<?php ? $var = new PDO(...);
它在文件开头和复制粘贴代码中相当普遍。如果您的代码在视觉上没有包含语法问题,请使用十六进制编辑器进行检查。
See also
也可以看看
回答by mario
Unexpected T_CONSTANT_ENCAPSED_STRING
Unexpected T_ENCAPSED_AND_WHITESPACE
意外的 T_CONSTANT_ENCAPSED_STRING
意外的 T_ENCAPSED_AND_WHITESPACE
The unwieldy names T_CONSTANT_ENCAPSED_STRING
and T_ENCAPSED_AND_WHITESPACE
refer to quoted "string"
literals.
笨拙的名称T_CONSTANT_ENCAPSED_STRING
和T_ENCAPSED_AND_WHITESPACE
引用引用的文字。"string"
They're used in different contexts, but the syntax issue are quite similar. T_ENCAPSED…warnings occur in double quoted string context, while T_CONSTANT…strings are often astray in plain PHP expressions or statements.
它们用于不同的上下文,但语法问题非常相似。T_ENCAPSED...警告出现在双引号字符串上下文中,而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 quotesfor array references:
echo "This is only $valid[here] ...";
Nested arrays or deeper object references however require the complex curly string expressionsyntax:
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 guessthat 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
\"
escapesfor 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
"
/'
quotesa recipe for parser errors:? make_url(login', 'open');
Here the
', '
would become a string literal after a bareword, when obviouslylogin
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.
不正确的变量插值
它最常出现在不正确的 PHP 变量插值中:
? ? echo "Here comes a $wrong['array'] access";
在 PHP 上下文中引用数组键是必须的。但在双引号字符串(或 HEREDOCs)中,这是一个错误。解析器抱怨包含的单引号
'string'
,因为它通常需要一个文字标识符/键。更准确地说,在数组引用的双引号内使用 PHP2 风格的简单语法是有效的:
echo "This is only $valid[here] ...";
然而,嵌套数组或更深层次的对象引用需要复杂的卷曲字符串表达式语法:
echo "Use {$array['as_usual']} with curly syntax.";
如果不确定,这通常使用起来更安全。它通常甚至被认为更具可读性。更好的 IDE 实际上为此使用了不同的语法着色。
缺少串联
如果字符串跟在表达式之后,但缺少连接或其他运算符,那么您会看到 PHP 抱怨字符串文字:
? print "Hello " . WORLD " !";
虽然这对您和我来说都很明显,但 PHP 无法猜测该字符串是要附加到那里的。
令人困惑的字符串引号外壳
混淆字符串分隔符时会发生相同的语法错误。以单引号
'
或双"
引号开头的字符串也以相同的结尾。? print "<a href="' . $link . '">click here</a>"; ????????????????????????????????????????
该示例以双引号开头。但是双引号也用于 HTML 属性。然而,其中的预期连接运算符被解释为单引号中第二个字符串的一部分。
提示:将您的编辑器/IDE 设置为对单引号和双引号字符串使用略微不同的着色。(它也有助于应用程序逻辑,例如将双引号字符串用于文本输出,单引号字符串仅用于类似常量的值。)
这是一个很好的例子,你不应该首先打破双引号。相反,只需对 HTML 属性的引号使用适当的
\"
转义:print "<a href=\"{$link}\">click here</a>";
虽然这也可能导致语法混乱,但所有更好的 IDE/编辑器都会通过对转义引号进行不同的着色来再次提供帮助。
缺少开场白
同样,忘记打开
"
/'
引用解析器错误的秘诀:? make_url(login', 'open');
在这里,the
', '
将成为一个裸字之后的字符串文字,login
而这显然是一个字符串参数。数组列表
如果
,
在数组创建块中遗漏了逗号,解析器将看到两个连续的字符串:array( ? "key" => "value" "next" => "....", );
请注意,最后一行可能总是包含一个额外的逗号,但忽略中间的一个是不可原谅的。如果没有语法突出显示,很难发现。
函数参数列表
同样的事情函数调用:
? myfunc(123, "text", "and" "more")
失控的弦
一个常见的变体是很容易被遗忘的字符串终止符:
? mysql_evil("SELECT * FROM stuffs); print "'ok'"; ?
在这里,PHP 抱怨两个字符串文字直接紧随其后。但真正的原因当然是未关闭的前一个字符串。
See also
也可以看看
回答by mario
Unexpected T_STRING
意外的 T_STRING
T_STRING
is a bit of a misnomer. It does not refer to a quoted "string"
. It means a raw identifier was encountered. This can range from bare
words to leftover CONSTANT
or function names, forgotten unquoted strings, or any plain text.
T_STRING
有点用词不当。它不指引用的"string"
. 这意味着遇到了原始标识符。这可以从bare
单词到剩余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 HEREDOCsection.
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 hereSee 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_STRING
s which the parser may protest then. Another frequent variation is anUnexpected '>'
for unquoted literal HTML.Non-programming string quotes
If you copy and pastecode from a blog or website, you sometimes end up with invalid code. Typographic quotes aren'twhat 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 scriptsThis 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 strayxml
was meant for. It'll get interpreted as constant. But theversion
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 PHPare represented by a dollar sign followed by the name of the variable.
The dollar sign (
$
) is a sigilthat marks the identifier as a name of a variable. Without this sigil, the identifier could be a language keywordor 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 printJim 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\\"
.
错误引用的字符串
但是,此语法错误对于错误引用的字符串值最常见。任何未转义和杂散
"
或'
引用将形成无效表达式:? ? echo "<a href="http://example.com">click here</a>";
语法高亮会使此类错误变得非常明显。重要的是要记住使用反斜杠来转义
\"
双引号或\'
单引号 - 取决于哪个用作字符串外壳。- 为方便起见,在输出带有双引号的纯 HTML 时,您应该更喜欢外单引号。
- 如果要插入变量,请使用双引号字符串,但要注意转义文字
"
双引号。 - 对于更长的输出,更喜欢多行
echo
/print
而不是转义进出。最好考虑一下HEREDOC部分。
另一个例子是在用 PHP 生成的 HTML 代码中使用 PHP 条目:
$text = '<div>some text with <?php echo 'some php entry' ?></div>'
如果
$text
有很多行并且开发人员没有看到整个 PHP 变量值并且专注于忘记其来源的代码段,则会发生这种情况。例子在这里未闭合的字符串
如果您错过了一个结束语,
"
那么语法错误通常会在稍后出现。未终止的字符串通常会消耗一些代码,直到下一个预期的字符串值:? echo "Some text", $a_variable, "and some runaway string ; success("finished"); ?
这不仅仅是
T_STRING
解析器可能会抗议的文字s 。另一个常见的变体是Unexpected '>'
用于不带引号的文字 HTML。非编程字符串引号
如果您从博客或网站复制和粘贴代码,有时最终会得到无效代码。排版引号不是PHP 所期望的:
$text = 'Something something..' + ”these ain't quotes”;
排版/智能引号是 Unicode 符号。PHP 将它们视为相邻字母数字文本的一部分。例如
”these
被解释为常量标识符。但是随后的任何文本文字都会被解析器视为裸字/T_STRING。缺少的分号;再次
如果您在前几行中有一个未终止的表达式,那么任何以下语句或语言结构都会被视为原始标识符:
? func1() function2();
PHP 只是不知道您是打算一个接一个地运行两个函数,还是打算将它们的结果相乘、相加、比较,或者只运行一个
||
或另一个。<?xml
PHP 脚本中的短打开标签和标题这是比较少见的。但是如果启用了 short_open_tags,那么您就不能以 XML 声明开始您的 PHP 脚本:
? <?xml version="1.0"?>
PHP 将看到
<?
并自行回收它。它不会明白流浪的xml
目的是什么。它会被解释为常量。但是version
将被视为另一个文字/常量。并且由于解析器无法理解中间没有表达式运算符的两个后续文字/值,这将是解析器失败。不可见的 Unicode 字符
语法错误的一个最可怕的原因是 Unicode 符号,例如不间断空格。PHP 允许使用 Unicode 字符作为标识符名称。如果您收到 T_STRING 解析器对完全不可疑的代码的投诉,例如:
<?php print 123;
您需要打破另一个文本编辑器。甚至是一个十六进制编辑器。这里看起来像普通的空格和换行符,可能包含不可见的常量。基于 Java 的 IDE 有时会忽略其中的 UTF-8 BOM、零宽度空格、段落分隔符等。尝试重新编辑所有内容,删除空格并重新添加正常空格。
您可以通过
;
在每行开头添加冗余语句分隔符来缩小范围:<?php ;print 123;
;
此处额外的分号会将前面的不可见字符转换为未定义的常量引用(表达式为语句)。作为回报,PHP 会产生有用的通知。变量名前缺少“$”符号
美元符号(
$
)是一个印记将标记的标识符作为变量的名称。如果没有这个符号,标识符可能是语言关键字或常量。当 PHP 代码从用另一种语言(C、Java、JavaScript 等)编写的代码“翻译”时,这是一个常见错误。在这种情况下,变量类型的声明(当原始代码是用使用类型变量的语言编写时)也可能偷偷溜走并产生此错误。
转义引号
如果
\
在字符串中使用,则具有特殊含义。这称为“转义字符”,通常会告诉解析器从字面上获取下一个字符。示例:
echo 'Jim said \'Hello\'';
将打印Jim said 'hello'
如果您对字符串的结束引号进行转义,则结束引号将按字面意思而不是按预期使用,即作为字符串的一部分作为可打印的引号而不是结束字符串。这通常会在您打开下一个字符串后或在脚本末尾显示为解析错误。
在 Windows 中指定路径时非常常见的错误:
"C:\xampp\htdocs\"
错误。你需要"C:\\xampp\\htdocs\\"
.
回答by mario
Unexpected (
意外 (
Opening parentheses typically follow language constructs such as if
/foreach
/for
/array
/list
or start an arithmetic expression. They're syntactically incorrect after "strings"
, a previous ()
, a lone $
, and in some typical declaration contexts.
左括号通常遵循语言结构,例如if
/ foreach
/ for
/ array
/list
或开始算术表达式。它们在 after "strings"
、 a previous ()
、 a lone$
以及一些典型的声明上下文中在语法上是不正确的。
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 syntaxwon'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()
andempty()
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.
函数声明参数
此错误较少发生的情况是尝试将表达式用作默认函数参数。这不受支持,即使在 PHP7 中:
function header_fallback($value, $expires = time() + 90000) {
函数声明中的参数只能是文字值或常量表达式。与函数调用不同,在函数调用中您可以自由使用
whatever(1+something()*2)
等。类属性默认值
对于同样的事情类成员的声明,其中只包含文字/常量是允许的,没有表情:
class xyz { ? var $default = get_config("xyz_default");
把这样的东西放在构造函数中。另请参阅为什么 PHP 属性不允许函数?
再次注意 PHP 7 只允许
var $xy = 1 + 2 +3;
常量表达式。PHP 中的 JavaScript 语法
出于显而易见的原因,使用 JavaScript 或jQuery 语法在 PHP 中不起作用:
<?php ? print $(document).text();
发生这种情况时,通常表示前面有一个未终止的字符串;和文字
<script>
部分泄漏到 PHP 代码上下文中。isset(())、空、键、下一个、当前
这两个
isset()
和empty()
是语言内置插件,而不是功能。他们需要直接访问一个变量。如果您无意中添加了过多的括号,那么您将创建一个表达式:? if (isset(($_GET["id"]))) {
这同样适用于需要隐式变量名称访问的任何语言构造。这些内置函数是语言语法的一部分,因此不允许使用装饰性的额外括号。
需要变量引用但获得传递的表达式结果的用户级函数反而会导致运行时错误。
Unexpected )
意外 )
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()
orlist()
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 statementsyou 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..
缺少函数参数
您不能在函数调用中最后出现杂散逗号。PHP 期望那里有一个值,因此抱怨过早的结束
)
括号。? callfunc(1, 2, );
尾随逗号只允许在
array()
orlist()
结构中。未完成的表达
如果您忘记了算术表达式中的某些内容,那么解析器就会放弃。因为它应该如何解释:
? $var = 2 * (1 + );
如果你
)
甚至忘记了结尾,那么你会收到关于意外分号的抱怨。Foreach作为
constant
↓ ? foreach ($array as wrong) {
PHP 有时会告诉你它期望一个
::
而不是。因为 class::$variable 可以满足预期的 $variable 表达式..
Unexpected {
意外 {
Curly braces {
and }
enclose code blocks. And syntax errors about them usually indicate some incorrect nesting.
花括号{
和}
括起来的代码块。并且关于它们的语法错误通常表明一些不正确的嵌套。
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.
不匹配的子表达式
if
最常见的不平衡
(
,并)
是因为如果解析器抱怨开幕花{
出现得太早。一个简单的例子:? if (($x == $y) && (2 == true) {
计算您的括号或使用有助于解决此问题的 IDE。也不要写没有任何空格的代码。可读性很重要。
{ 和 } 在表达式上下文中
不能在表达式中使用花括号。如果将括号和花括号混淆,则不符合语言语法:
? $var = 5 * {7 + $x};
标识符构造有一些例外,例如局部作用域变量
${references}
。变量变量或卷曲 var 表达式
这是非常罕见的。但是您也可能会收到
{
和}
解析器对复杂变量表达式的抱怨:? print "Hello {$world[2{]} !";
尽管
}
在这种情况下出现意外的可能性更高。
Unexpected }
意外 }
When getting an "unexpected }
" error, you've mostly closed a code block too early.
当遇到“意外}
”错误时,您大多过早关闭了代码块。
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.
代码块中的最后一条语句
任何未终止的表达式都可能发生这种情况。
如果函数/代码块中的最后一行缺少尾随
;
分号:function whatever() { doStuff() } ?
在这里,解析器无法判断您是否还想添加
+ 25;
到函数结果或其他内容中。无效的块嵌套/被遗忘
{
当代码块
}
过早关闭时,您有时会看到此解析器错误,或者您{
甚至忘记了开头:function doStuff() { if (true) ? print "yes"; } } ?
在上面的代码片段中,
if
没有{
左花括号。因此,}
下面的结尾变得多余了。因此}
,用于该函数的下一个结束与最初的左{
花括号没有关联。如果没有适当的代码缩进,这样的错误就更难发现。使用 IDE 和括号匹配。
Unexpected {
, expecting (
出乎意料{
,期待(
Language constructs which require a condition/declaration header anda code block will trigger this error.
需要条件/声明标头和代码块的语言结构将触发此错误。
Parameter lists
For example misdeclared functions without parameter listare not permitted:
? function whatever { }
Control statement conditions
And you can't likewise have an
if
without condition.? if { }
Which doesn't make sense, obviously. The same thing for the usual suspects,
for
/foreach
,while
/do
, etc.If you've got this particular error, you definitely should look up some manual examples.
参数列表
例如,不允许错误声明没有参数列表的函数:
? function whatever { }
控制语句条件
而且你也不能有一个
if
无条件的。? if { }
这显然没有意义。对于通常的嫌疑犯,
for
/foreach
,while
/do
等也是同样的事情。如果您遇到此特定错误,则绝对应该查找一些手动示例。
回答by mario
Unexpected $end
意外的 $end
When PHP talks about an "unexpected $end
", it means that your code ended prematurely. (The message is a bit misleading when taken literally. It's not about a variable named "$end", as sometimes assumed by newcomers. It refers to the "end of file", EOF.)
当 PHP 谈到“意外$end
”时,意味着您的代码过早结束。(从字面上看,该消息有点误导。它不是关于名为“$end”的变量,正如新人有时假设的那样。它指的是“文件结尾”,EOF。)
Cause:Unbalanced
{
and}
for code blocks / and function or class declarations.
原因:不平衡
{
和}
代码块/和函数或类声明。
It's pretty much alwaysabout a missing }
curly brace to close preceding code blocks.
它几乎总是出现缺少}
大括号,关闭前面的代码块。
Again, use proper indentation to avoid such issues.
Use an IDE with bracket matching, to find out where the
}
is amiss. There are keyboard shortcuts in most IDEs and text editors:- NetBeans, PhpStorm, Komodo: Ctrl[and Ctrl]
- Eclipse, Aptana: CtrlShiftP
- Atom, Sublime: Ctrlm- Zend Studio CtrlM
- Geany, Notepad++: CtrlB- Joe: CtrlG- Emacs: C-M-n- Vim: %
同样,使用适当的缩进来避免此类问题。
使用带有括号匹配的 IDE,找出
}
错误的地方。大多数 IDE 和文本编辑器中都有键盘快捷键:- NetBeans、PhpStorm、Komodo:Ctrl[和Ctrl]
- Eclipse,Aptana: CtrlShiftP
- Atom, Sublime: Ctrlm- Zend StudioCtrlM
- Geany, Notepad++: CtrlB- Joe: CtrlG- Emacs: C-M-n- Vim:%
Most IDEs also highlightmatching braces, brackets and parentheses. Which makes it pretty easy to inspect their correlation:
大多数 IDE 还会突出显示匹配的大括号、方括号和圆括号。这使得检查它们的相关性变得非常容易:
Unterminated expressions
未终止的表达式
And Unexpected $end
syntax/parser error can also occur for unterminated expressions or statements:
而且Unexpected $end
也可以发生语法/分析器错误未结束的表达式或语句:
$var = func(1,
?>
EOF
$var = func(1,
?>
EOF
So, look at the end of scripts first. A trailing ;
is often redundant for the last statement in any PHP script. But you shouldhave one. Precisely because it narrows such syntax issues down.
所以,首先看看脚本的结尾。;
对于任何 PHP 脚本中的最后一条语句,尾随通常是多余的。但你应该有一个。正是因为它缩小了此类语法问题的范围。
Indented HEREDOC markers
缩进的 HEREDOC 标记
Another common occurrence appears with HEREDOC or NOWDOCstrings. The terminating marker goes ignored with leading spaces, tabs, etc.:
另一个常见的情况出现在HEREDOC 或 NOWDOC字符串中。终止标记被前导空格、制表符等忽略:
print <<< END
Content...
Content....
END;
# ↑ terminator isn't exactly at the line start
Therefore the parser assumes the HEREDOC string to continue until the end of the file (hence "Unexpected $end"). Pretty much all IDEs and syntax-highlighting editors will make this obvious or warn about it.
因此,解析器假定 HEREDOC 字符串一直持续到文件结尾(因此是“意外的 $end”)。几乎所有的 IDE 和语法高亮编辑器都会使这一点变得明显或警告它。
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'
示例:echo 'Jim said \'Hello\'';
将打印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\\"
.
在 Windows 中指定路径时非常常见的错误:"C:\xampp\htdocs\"
错误。你需要"C:\\xampp\\htdocs\\"
.
Alternative syntax
替代语法
Somewhat rarer you can see this syntax error when using the alternative syntax for statement/code blocks in templates. Using if:
and else:
and a missing endif;
for example.
在模板中使用语句/代码块的替代语法时,您会看到这种语法错误的情况比较少见。例如,使用if:
和else:
和缺失endif;
。
See also:
也可以看看:
- PHP syntax error “unexpected $end”
- Parse error: Syntax error, unexpected end of file in my PHP code
- Parse error syntax error unexpected end of file, using PHP
- PHP Parse error: syntax error, unexpected end of file in a CodeIgniter View
- Parse error: syntax error, unexpected end of file (Registration script)
- "Parse error: syntax error, unexpected $end" For my uni registration assignment
- Fixing PHP Errors: PHP Error #3: Unexpected end of file
回答by mario
Unexpected T_IF
Unexpected T_ELSEIF
Unexpected T_ELSE
Unexpected T_ENDIF
意外的 T_IF
意外的 T_ELSEIF
意外的 T_ELSE
意外的 T_ENDIF
Conditional control blocks if
, elseif
and else
follow a simple structure. When you encounter a syntax error, it's most likely just invalid block nesting → with missing {
curly braces }
- or one too many.
条件控制块if
,elseif
并else
遵循简单的结构。当您遇到语法错误时,很可能只是无效的块嵌套 → 缺少{
大括号}
- 或者太多。
Missing
{
or}
due to incorrect indentationMismatched 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 expressionsA 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
if
s andecho
s.
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
(oror
) already allows chaining comparisons.Forgotten
;
semicolonsOnce 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 theif
, and would always run. - So the
else
no longer had a relation to an openif
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 wholeif
construct, severing theelse
branch syntactically.- When you terminate the
Not using code blocks
It's syntactically allowed to omit curly braces
{
…}
for code blocks inif
/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 haveto 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
elseif
s as you want, butelse
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 functiondefinition, or closed one
}
too early in such cases.Unexpected T_ELSEIF / T_ELSE
When mixing PHP and HTML, the closing
}
for anif/elseif
must be in the same PHP block<?php ?>
as the nextelseif/else
. This will generate an error as the closing}
for theif
needs to be part of theelseif
:<?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 inbetweenif
andelseif
/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
andelse
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/elsebetween different control structures:
foreach ($array as $i) { if ($i) { … } } else { … }
There is no syntactic relationbetween the
if
andelse
. Theforeach
lexical scope ends at}
, so there's no point for theif
structure to continue.- This wouldn't make sense anyway. It's not like that there was some "undefined" state when PHP jumps between
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 anyif:
.Using
} endif;
is a doubledif
-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.
缺少
{
或}
由于缩进不正确不匹配的代码大括号对于格式不太好的代码很常见,例如:
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/else 条件及其
{
代码块的嵌套结构和关系,您将只能修复它}
。使用您的 IDE 查看它们是否都已配对。if (true) { if (false) { … } elseif ($whatever) { if ($something2) { … } else { … } } else { … } if (false) { // a second `if` tree … } else { … } } elseif (false) { … }
任何 double 不仅
}
}
会关闭分支,还会关闭先前的条件结构。因此坚持一种编码风格;不要在嵌套的 if/else 树中混合和匹配。除了这里的一致性之外,事实证明避免冗长的条件也很有帮助。使用临时变量或函数来避免不可读
if
的表达式。IF
不能在表达式中使用一个令人惊讶的常见错误是尝试
if
在表达式中使用语句,例如打印语句:? echo "<a href='" . if ($link == "example.org") { echo …
这当然是无效的。
您可以使用三元条件,但要注意可读性影响。
echo "<a href='" . ($link ? "http://yes" : "http://no") . "</a>";
否则打破这样的输出结构:使用多个
if
s 和echo
s。
更好的是,使用临时变量,并将您的条件放在之前:if ($link) { $href = "yes"; } else { $href = "no"; } echo "<a href='$href'>Link</a>";
为这种情况定义函数或方法通常也很有意义。
控制块不返回“结果”
现在这不太常见,但一些编码人员甚至尝试将其
if
视为可以返回结果:$var = if ($x == $y) { "true" };
这在结构上与
if
在字符串连接/表达式中使用相同。- 但是控制结构(if / foreach / while)没有“结果”。
- 文字字符串“true”也只是一个 void 语句。
您必须在代码块中使用赋值:
if ($x == $y) { $var = "true"; }
或者,诉诸
?:
三元比较。如果在如果
? if ($x == true and (if $y != false)) { ... }
这显然是多余的,因为
and
(oror
) 已经允许链接比较。忘记
;
分号再说一遍:每个控制块都需要是一个语句。如果前面的代码段没有以分号结尾,那么这是一个有保证的语法错误:
? $var = 1 + 2 + 3 if (true) { … }
顺便说一句,
{…}
代码块中的最后一行也需要一个分号。分号过早
现在责怪特定的编码风格可能是错误的,因为这个陷阱太容易被忽视了:
? if ($x == 5); { $y = 7; } else ← { $x = -1; }
这比你想象的更频繁。
- 当你用它终止
if ()
表达式时,;
它会执行一个 void 语句。在;
成为空{}
了自己的! {…}
因此,该块与 分离if
,并且将始终运行。- 所以
else
不再与开放if
结构有关系,这就是为什么这会导致意外的 T_ELSE 语法错误。
这也解释了这个语法错误的一个同样微妙的变化:
if ($x) { x_is_true(); }; else { something_else(); };
在
;
代码块之后{…}
终止整个if
构造的地方,在else
语法上切断分支。- 当你用它终止
不使用代码块
它的语法允许省略花括号
{
...}
在代码块if
/elseif
/else
枝。遗憾的是,这是一种对于不熟悉的编码人员来说非常常见的语法风格。(在错误的假设下,这会更快地输入或阅读)。但是,这很可能会破坏语法。迟早会有其他语句进入 if/else 分支:
if (true) $x = 5; elseif (false) $x = 6; $y = 7; ← else $z = 0;
但要实际使用代码块,您必须编写
{
……}
它们!即使是经验丰富的程序员也会避免这种无括号语法,或者至少将其理解为规则的例外情况。
Else / Elseif 顺序错误
当然,要提醒自己的一件事是条件顺序。
if ($a) { … } else { … } elseif ($b) { … } ↑
您可以拥有任意数量的
elseif
s,但else
必须放在最后。就是这样。类声明
正如上面提到的,你不能在一个类中声明的控制语句:
class xyz { if (true) { function ($var) {} }
意外的 T_ELSEIF / T_ELSE
混合使用 PHP 和 HTML 时,
}
an的结尾if/elseif
必须<?php ?>
与下一个elseif/else
. 这将产生错误的闭合}
的if
需要是部分elseif
:<?php if ($x) { ?> html <?php } ?> <?php elseif ($y) { ?> html <?php } ?>
正确的形式
<?php } elseif
:<?php if ($x) { ?> html <?php } elseif ($y) { ?> html <?php } ?>
这或多或少是不正确缩进的变体——大概通常基于错误的编码意图。
你不能混搭其他语句其间if
和elseif
/else
结构标记:if (true) { } echo "in between"; ← elseif (false) { } ?> text <?php ← else { }
{…}
两者都只能出现在代码块中,不能出现在控制结构标记之间。- 这无论如何都没有意义。当 PHP 在
if
和else
分支之间跳转时,并不是有一些“未定义”的状态。 - 您必须决定打印语句属于 / 的位置,或者它们是否需要在两个分支中重复。
您也不能在不同的控制结构之间分离if/else:
foreach ($array as $i) { if ($i) { … } } else { … }
和之间没有句法关系。将在词法范围结束,所以没有点的结构继续。
if
else
foreach
}
if
- 这无论如何都没有意义。当 PHP 在
T_ENDIF
如果抱怨出现意外的 T_ENDIF,您使用的是替代语法样式
if:
?elseif:
?else:
?endif;
. 你真的应该三思而后行。一个常见的陷阱是将异常相似的
:
冒号与;
分号混淆。(包含在“分号过早”中)由于缩进在模板文件中更难跟踪,因此在使用替代语法时越多 - 您可能
endif;
不匹配任何if:
.Using
} endif;
是一个双重的 -if
终止符。
虽然“意外的 $end”通常是被遗忘的结束
}
花括号的价格。分配与比较
因此,这不是语法错误,但在此上下文中值得一提:
? if ($x = true) { } else { do_false(); }
那不是
==
/===
比较,而是=
赋值。这是相当微妙的,很容易导致一些用户无助地编辑整个条件块。首先注意意外分配 - 每当您遇到逻辑错误/不当行为时。
回答by mario
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 >
意外的 T_IS_EQUAL
意外的 T_IS_GREATER_OR_EQUAL
意外的 T_IS_IDENTICAL
意外的 T_IS_NOT_EQUAL
意外的 T_IS_NOT_IDENTICAL
意外的 T_IS_SMALLER_OR_EQUAL
意外的<
意外>
Comparison operators such as ==
, >=
, ===
, !=
, <>
, !==
and <=
or <
and >
mostly should be used just in expressions, such as if
expressions. If the parser complains about them, then it often means incorrect paring or mismatched (
)
parens around them.
比较运算符,例如==
, >=
, ===
, !=
, <>
,!==
和<=
or <
and>
大多数情况下应该只在表达式中使用,例如if
表达式。如果解析器抱怨它们,那么这通常意味着(
)
它们周围的配对不正确或不匹配。
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()
orempty()
with comparisons:? if (empty($_POST["var"] == 1)) {
Or even:
? if (isset($variable !== "value")) {
This doesn't make sense to PHP, because
isset
andempty
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 operatorBoth 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 thanor 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 customT_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 constantHello
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(); ?> ↑
父母分组
特别是对于
if
具有多重比较的语句,您必须注意正确计算左括号和右括号:? if (($foo < 7) && $bar) > 5 || $baz < 9) { ... } ↑
这里的
if
条件已经被终止了)
一旦您的比较变得足够复杂,通常有助于将其拆分为多个嵌套
if
结构。isset() 与比较混合
一个常见的新人是 pitfal 试图结合
isset()
或empty()
比较:? if (empty($_POST["var"] == 1)) {
甚至:
? if (isset($variable !== "value")) {
这对 PHP 没有意义,因为
isset
和empty
是只接受变量名的语言结构。比较结果也没有意义,因为输出只是/已经是布尔值。将
>=
大于或等于与=>
数组运算符混淆这两个运算符看起来有些相似,所以它们有时会混淆:
? if ($var => 5) { ... }
你只需要记住这个比较运算符被称为“大于或等于”就可以了。
另请参阅:PHP 中的 If 语句结构
没有什么可比的
如果它们属于相同的变量名称,您也不能组合两个比较:
? if ($xyz > 5 and < 100)
PHP 无法推断出您打算再次比较初始变量。表达式通常根据运算符优先级配对,因此在
<
看到 时,原始变量只剩下一个布尔结果。比较链
您不能用一行运算符与变量进行比较:
? $reult = (5 < $x < 10);
这必须分解为两个比较,每个比较针对
$x
.这实际上更像是被列入黑名单的表达式的情况(由于等效的运算符关联性)。它在一些 C 风格的语言中在语法上是有效的,但 PHP 也不会将它解释为预期的比较链。
意外的
>
意外<
大于
>
或小于<
运算符没有自定义T_XXX
标记器名称。虽然它们可能像其他所有东西一样被放错位置,但您更经常看到解析器抱怨它们被错误引用的字符串和混搭的 HTML:? print "<a href='z">Hello</a>"; ↑
这相当于将字符串
"<a href='z"
与>
文字常量进行比较Hello
,然后再<
进行比较。或者这至少是 PHP 的看法。实际原因和语法错误是过早的字符串"
终止。也不能嵌套 PHP 开始标签:
<?php echo <?php my_func(); ?> ↑
See also:
也可以看看: