PHP 解析/语法错误;以及如何解决它们
每个人都会遇到语法错误。即使是经验丰富的程序员也会犯错。对于新人来说,这只是学习过程的一部分。但是,通常很容易解释错误消息,例如:
PHP 解析错误:语法错误,index.php 第 20 行出现意外的“{”
意外的符号并不总是真正的罪魁祸首。但行号给出了从哪里开始寻找的粗略想法。
始终查看代码上下文。语法错误通常隐藏在前面的代码行中提到的或中。将您的代码与手册中的语法示例进行比较。
虽然并非每个案例都相互匹配。不过,有一些一般步骤可以解决语法错误。 此参考文献总结了常见的陷阱:
-
意外的 T_FUNCTION...< /p>
-
意外的 T_IF
意外的 T_FOREACH
意外的 T_FOR
意外T_WHILE
意外 T_DO
意外 T_PRINT
意外 T_ECHO -
<一href="//stackoverflow.com/a/47202089">意外的 T_LNUMBER
- < p>意外的 T_OBJECT_OPERATOR...
-
意外的 T_SL...
-
意外的“公共”(T_PUBLIC)
意外的“私人”(T_PRIVATE) < br> 意外的“受保护”(T_PROTECTED)
意外的“最终” (T_FINAL)... -
意外的 T_CLASS...< /p>
-
<一href="https://stackoverflow.com/questions/27783613/parse-error-syntax-error-unexpected-t-dnumber-in-home-a3206525-public-html-ea">意外的 T_DNUMBER
-
<一href="https://stackoverflow.com/questions/29241208/php-parse-error-syntax-error-unexpected-in">意外的
,
(逗号)< /em> -
未执行的
。
(句号)< /em> -
意外的
;
(分号) -
意外
*
(星号) -
意外的
:
(冒号) -
意外的
&
(调用时间传递引用)
密切相关的参考文献:
并且:
- PHP 手册php.net 及其各种语言标记
- 或维基百科的PHP 语法介绍。
- 最后当然是我们的php tag-wiki。
虽然 Stack Overflow 也欢迎新手程序员,但它主要针对专业编程问题。
- 回答每个人的编码错误和狭隘的拼写错误大多被认为是偏离主题的。
- 因此,在发布语法修复请求之前,请花一些时间遵循基本步骤。
- 如果您仍然需要这样做,请展示您自己的解决方案、尝试的修复以及您对看似错误或可能错误的思考过程。
如果您的浏览器显示错误消息,例如“SyntaxError:非法字符”,那么它实际上并不是php 相关,但是 javascript-语法错误。
供应商代码引发的语法错误:最后,请考虑,如果语法错误不是通过编辑代码库引发的,而是在外部供应商软件包安装或升级后引发的,则可能是由于 PHP 版本不兼容所致,因此根据您的平台设置检查供应商的要求。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(21)
对于 VS Code 的新手,如果您看到语法错误,请检查您是否已保存文件。如果语法错误,请保存文件,然后修复语法而不再次保存,VS Code 将继续向您显示错误。只有保存文件后,错误消息才会消失。
For newbies to VS Code, if you see the syntax error, check if you have saved the file. If you have a wrong syntax, save the file, and then fix the syntax withou saving again, VS Code will keep showing you the error. The error message will disappear only after you save the file.
必须使用 IDE 来避免语法错误,但也必须使用 PHPStan 或 PHPCS 等工具来确保您以与团队同事相同的方式进行编码,并且代码缩进良好。
如果没有这个工具,您(或您的同事)只需更改几行,就可以在 github 评论中发现大量更改。
您还可以配置您的提交,以便在提交之前与 CSSLint 或 ESLint 等其他工具一起运行这些工具,以确保一切正常(具体而言)。
An IDE is mandatory to avoid sintax error, but tools like PHPStan or PHPCS are also mandatory to be sure you are coding in the same way your team colleagues ande your code is well indented.
Without this tools you (or your colleagues) could find tons of changes in github reviews when just a few lines were changed.
You can configure your commits as well to run these tools with others like CSSLint or ESLint before committing to be sure everything's fine (sintatically speaking).
有哪些语法错误?
PHP 属于 C 风格 和 命令式编程语言。它具有严格的语法规则,当遇到放错位置的符号或标识符时无法恢复。它无法猜测您的编码意图。
最重要的提示
您可以随时采取一些基本的预防措施:
使用正确的代码缩进,或采用任何高级的编码风格。
可读性可以防止不规则性。
使用 IDE 或 PHP 编辑器< /a> 带有语法突出显示。
这也有助于括号/括号平衡。
阅读 手册中的语言参考和示例。
两次,变得有点熟练。
如何解释解析器错误
典型的语法错误消息如下:
其中列出了可能语法错误的位置。请参阅提到的文件名和行号。
名字(例如
T_STRING
)解释了解析器/标记器最终无法处理哪个符号。然而,这不一定是语法错误的原因。查看以前的代码行也很重要。通常,语法错误只是之前发生的意外。错误行号正是解析器最终放弃处理所有内容的位置。
解决语法错误
有许多方法可以缩小和修复语法问题。
打开提到的源文件。查看提到的代码行。
对于失控的字符串和错位的运算符,这通常是您找到罪魁祸首的地方。
从左到右阅读该行并想象每个符号的作用。
您还需要更频繁地查看前面的行。
特别是,上一行结尾/语句处缺少
;
分号。 (至少从风格的角度来看。)如果
{
代码块}
未正确关闭或嵌套,您可能需要进一步调查源代码。使用适当的代码缩进来简化。看看语法着色!
字符串、变量和常量都应该有不同的颜色。
运算符
+-*/.
也应该着色不同。否则他们可能处于错误的环境中。如果您发现字符串着色延伸得太远或太短,则说明您发现了未转义或丢失的结束
"
或'
字符串标记。两个相邻的相同颜色的标点符号也可能意味着麻烦。通常,如果运算符后面不是
++
、--
或括号,则运算符是单独的。在大多数情况下,两个直接相连的字符串/标识符是不正确的。空白是你的朋友。
遵循任何编码风格。
暂时打破长队。
您可以在运算符或常量和字符串之间自由添加换行符。然后解析器将具体化解析错误的行号。您可以隔离丢失或放错位置的语法符号,而不是查看非常冗长的代码。
将复杂的
if
语句拆分为不同的或嵌套的if
条件。不要使用冗长的数学公式或逻辑链,而是使用临时变量来简化代码。 (更具可读性=更少的错误。)
在以下位置之间添加换行符:
对长代码块进行分区确实有助于定位语法错误的根源。
注释掉违规代码。
如果无法隔离问题根源,请开始注释掉(从而暂时删除)代码块。
一旦解决了解析错误,您就找到了问题根源。仔细看看那里。
有时您想暂时删除完整的函数/方法块。 (如果出现不匹配的大括号和错误缩进的代码。)
当您无法解决语法问题时,请尝试从头开始重写注释掉的部分。
作为新手,请避免一些令人困惑的语法结构。
三元
? :
条件运算符可以压缩代码并且确实很有用。但它并不能在所有情况下提高可读性。在不熟悉的情况下更喜欢简单的if
语句。PHP 的替代语法 (
if:
/elseif:
/endif;
) 对于模板来说很常见,但可以说不太容易遵循正常的{
代码}
块。新手最常见的错误是:
缺少用于终止语句/行的分号
;
。"
或'
的字符串引号不匹配,且其中未转义引号。被遗忘的运算符,特别是字符串
.
连接。不平衡
(
括号)
。在报告的行中对它们进行计数。它们的数量相等吗?不要忘记解决一个语法问题可以发现下一个语法问题。
如果您解决了一个问题,但下面的某些代码中突然出现了其他问题,那么您基本上就走在正确的道路上了。
如果编辑后同一行中出现新的语法错误,那么您尝试的更改可能会失败。 (但并不总是如此。)
如果无法修复以前工作的代码,请恢复它的备份。
差异
。这可能有助于了解语法问题是什么。看不见的杂散 Unicode 字符:在某些情况下,您需要 在源代码上使用十六进制编辑器或其他编辑器/查看器。有些问题仅仅通过查看代码是无法发现的。
尝试
grep --color -P -n "\[\x80-\xFF\]" file.php
作为查找非 ASCII 符号的第一个措施。特别是 BOM、零宽度空格或不间断空格以及智能引号通常会出现在源代码中。
注意文件中保存的换行符类型。
PHP 仅支持 \n 换行符,而不支持 \r 回车符。
对于 MacOS 用户来说,这有时会是一个问题(即使是在 OS X 上,对于配置错误的编辑器也是如此)。
通常只有在使用单行
//
或#
注释时才会出现问题。当忽略换行符时,多行/*...*/
注释很少会干扰解析器。如果您的语法错误未通过网络传输:
您的机器上碰巧有语法错误。但在线发布相同的文件不再显示它。这只能意味着以下两件事之一:
您正在查看错误的文件!
或者您的代码包含不可见的杂散 Unicode(见上文)。
您可以轻松发现:只需将代码从网络表单复制回文本编辑器即可。
检查您的PHP 版本。并非所有语法结构在每个服务器上都可用。
php -v
用于命令行解释器用于通过网络服务器调用。
这些不一定相同。特别是在使用框架时,您需要将它们匹配。
不要使用PHP 的保留关键字作为函数/方法、类或常量的标识符。
试错是你最后的手段。
如果其他方法均失败,您可以随时 google 您的错误消息。语法符号不太容易搜索(尽管 Stack Overflow 本身是通过 SymbolHound 进行索引的)。因此,您可能需要再浏览几页才能找到相关内容。
更多指南:
白屏死机
如果您的网站一片空白,那么通常是语法错误造成的。
启用它们的显示:
error_reporting = E_ALL
display_errors = 1
在您的
php.ini
通常,或通过.htaccess
,甚至
.user.ini
使用 FastCGI 设置。在损坏的脚本中启用它为时已晚,因为 PHP 甚至无法解释/运行第一行。一个快速的解决方法是制作一个包装器脚本,例如
test.php
:然后通过访问此包装器脚本来调用失败的代码。
它还有助于启用 PHP 的
error_log
并查看您的 网络服务器的error.log
当脚本因 HTTP 500 响应而崩溃时。What are the syntax errors?
PHP belongs to the C-style and imperative programming languages. It has rigid grammar rules, which it cannot recover from when encountering misplaced symbols or identifiers. It can't guess your coding intentions.
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 IDE or editor for PHP with syntax highlighting.
Which also help with parentheses/bracket balancing.
Read the language reference and examples in the manual.
Twice, to become somewhat proficient.
How to interpret parser errors
A typical syntax error message reads:
Which lists the possible location of a syntax mistake. See the mentioned file name and line number.
A moniker such as
T_STRING
explains which symbol the parser/tokenizer couldn't process finally. This isn't necessarily the cause of the syntax mistake, however.It's important to look into previous code lines as 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 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 nestedif
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 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.
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:
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
In your
php.ini
generally, or via.htaccess
for mod_php,or even
.user.ini
with FastCGI setups.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
:Then invoke the failing code by accessing this wrapper script.
It also helps to enable PHP's
error_log
and look into your webserver'serror.log
when a script crashes with HTTP 500 responses.我认为这个话题完全讨论过度/过于复杂。使用 IDE 是完全避免任何语法错误的方法。我什至会说,在没有 IDE 的情况下工作是一种不专业的行为。为什么?因为现代 IDE 在您键入每个字符后都会检查您的语法。当您编码并且整行变成红色,并且一个大警告通知显示语法错误的确切类型和确切位置时,那么绝对不需要搜索其他解决方案。
使用语法检查 IDE 意味着:
您将(有效地)再也不会遇到语法错误,因为您在键入时可以正确地看到它们。说真的。
具有语法检查功能的优秀 IDE(它们都适用于 Linux、Windows 和 Mac):
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.
Using a syntax-checking IDE means:
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):
意外的
[
如今,意外的
[
数组括号在过时的 PHP 版本中很常见。 短数组语法自 PHP = 5.4 起可用。较旧的安装仅支持array()
。数组函数结果解引用同样不适用于较旧的 PHP 版本:
参考 - 这个错误在 PHP 中意味着什么? -“语法错误,意外的
\[
”显示了最常见和实用的解决方法。不过,升级 PHP 安装总是更好的选择。对于共享虚拟主机计划,首先研究是否可以使用
SetHandler php56-fcgi
来启用更新的运行时。另请参阅:
顺便说一句,还有预处理器和 PHP 5.4 语法下转换器(如果您确实坚持使用较旧且速度较慢的 PHP 版本)。
导致意外
[
语法错误的其他原因如果不是 PHP 版本不匹配,那么通常是简单的拼写错误或新手语法错误:
你不能使用类中的数组属性声明/表达式,即使在 PHP 7 中也不行。
将
[
与左大括号{
或圆括号(
混淆是一种常见的疏忽。或者甚至:
或者尝试将常量(PHP 5.6 之前)作为数组取消引用:
至少 PHP 将
const
解释为常量名称。如果您打算访问数组变量(这是此处的典型原因),请添加前导
$
符号 - 这样它就变成$varname
。您正在尝试对关联数组的成员使用
global
关键字。这不是有效的语法:意外的
]
结束方括号这种情况比较罕见,但终止数组
] 支架。
与
)
括号或}
大括号的不匹配很常见:或者尝试结束没有括号的数组:
<前><代码>$var = 2];
这通常出现在多行和嵌套数组声明中。
如果是这样,请使用 IDE 进行括号匹配来查找任何过早的
]
数组闭包。至少使用更多的间距和换行符来缩小范围。Unexpected
[
These days, the unexpected
[
array bracket is commonly seen on outdated PHP versions. The short array syntax is available since PHP >= 5.4. Older installations only supportarray()
.Array function result dereferencing is likewise not available for older PHP versions:
Reference - What does this error mean in PHP? - "Syntax error, unexpected
\[
" shows the most common and practical workarounds.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.See also:
BTW, there are also preprocessors and PHP 5.4 syntax down-converters if you're really clingy with older + slower PHP versions.
Other causes for Unexpected
[
syntax errorsIf it's not the PHP version mismatch, then it's oftentimes a plain typo or newcomer syntax mistake:
You can't use array property declarations/expressions in classes, not even in PHP 7.
Confusing
[
with opening curly braces{
or parentheses(
is a common oversight.Or even:
Or trying to dereference constants (before PHP 5.6) as arrays:
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:Unexpected
]
closing square bracketThis is somewhat rarer, but there are also syntax accidents with the terminating array
]
bracket.Again mismatches with
)
parentheses or}
curly braces are common:Or trying to end an array where there isn't one:
Which often occurs in multi-line and nested array declarations.
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.意外的 T_VARIABLE
“意外的
T_VARIABLE
” 意味着存在一个文字$variable
名称,它不适合当前的表达式/语句结构。缺少分号
它通常表示上一行中缺少分号。语句后面的变量赋值是一个很好的指示符:
<前><代码> ⇓
函数1()
$var = 1 + 2; # +2行解析错误
字符串连接
常见的错误是字符串连接< /a> 与忘记的
.
运算符:<前><代码> ⇓
print "值来了:" $value;
顺便说一句,您应该更喜欢字符串插值(双精度中的基本变量引号)只要有助于可读性。这避免了这些语法问题。
<块引用>
字符串插值是脚本语言的核心功能。使用它并不羞耻。忽略任何关于变量
.
串联更快的微优化建议。 不是。缺少表达式运算符
当然,在其他表达式中也可能出现同样的问题,例如算术运算:
<前><代码> ⇓
打印 4 + 7 $var;
PHP 无法在这里猜测变量是否应该被添加、减去或比较等。
列表< /h3>
对于语法列表也是如此,就像在数组总体中一样,解析器还指示预期的逗号
,
例如:<前><代码> ⇓
$var = array("1" => $val, $val2, $val3 $val4);
或者函数参数列表:
<前><代码> ⇓
函数 myfunc($param1, $param2 $param3, $param4)
同样,您是否会在
list
或global
语句中看到此情况,或者在for
中缺少;
分号时看到这一点> 循环。类声明
也会出现此解析器错误在类声明中。您只能分配静态常量,而不能分配表达式。因此解析器抱怨变量作为分配的数据:
不匹配的
}
右大括号尤其可能导致这里。如果方法过早终止(使用适当的缩进!),那么杂散变量通常会被错误地放入类声明主体中。标识符后的变量
您也不能直接让变量跟随标识符:< /p>
<前><代码> ⇓
$this->myFunc$VAR();
顺便说一句,这是一个常见的示例,其目的可能是使用变量。在本例中,使用
$this->{"myFunc$VAR"}();
进行变量属性查找。<块引用>
请记住,使用可变变量应该是例外。新手经常尝试过于随意地使用它们,即使数组更简单、更合适。
语言构造后缺少括号
仓促打字可能会导致忘记左括号或右括号
for
if
和for
和foreach
语句:<前><代码> ⇓
foreach $array 作为 $key) {
解决方案:在语句和变量之间添加缺少的开头
(
。<前><代码> ⇓
如果($var = pdo_query($sql){
$结果 = ...
大括号
{
不会打开代码块,除非先用)
右括号关闭if
表达式。否则不期望条件
<前><代码> ⇓
否则($var>=0)
解决方案:从
else
中删除条件或使用elseif
。需要括号来关闭
<前><代码> ⇓
function() 使用 $var {}
解决方案:在
$var
两边添加括号。不可见的空白
正如关于“Invisible stray Unicode”的参考答案中提到的(例如不间断空格),您可能还会在毫无戒心的代码中看到此错误,例如:
<前><代码>
它在文件开头和复制粘贴代码中相当普遍。如果您的代码在视觉上看起来不包含语法问题,请使用十六进制编辑器进行检查。
另请参阅
Unexpected T_VARIABLE
An "unexpected
T_VARIABLE
" means that there's a literal$variable
name, which doesn't fit into the current expression/statement structure.Missing semicolon
It most commonly indicates a missing semicolon in the previous line. Variable assignments following a statement are a good indicator where to look:
String concatenation
A frequent mishap are string concatenations with forgotten
.
operator:Btw, you should prefer string interpolation (basic variables in double quotes) whenever that helps readability. Which avoids these syntax issues.
Missing expression operators
Of course the same issue can arise in other expressions, for instance arithmetic operations:
PHP can't guess here if the variable should have been added, subtracted or compared etc.
Lists
Same for syntax lists, like in array populations, where the parser also indicates an expected comma
,
for example:Or functions parameter lists:
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:
Unmatched
}
closing curly braces can in particular lead here. If a method is terminated too early (use proper indentation!), then a stray variable is commonly misplaced into the class declaration body.Variables after identifiers
You can also never have a variable follow an identifier directly:
Btw, this is a common example where the intention was to use variable variables perhaps. In this case a variable property lookup with
$this->{"myFunc$VAR"}();
for example.Missing parentheses after language constructs
Hasty typing may lead to forgotten opening or closing parenthesis
for
if
andfor
andforeach
statements:Solution: add the missing opening
(
between statement and variable.The curly
{
brace does not open the code block, without closing theif
expression with the)
closing parenthesis first.Else does not expect conditions
Solution: Remove the conditions from
else
or useelseif
.Need brackets for closure
Solution: Add brackets around
$var
.Invisible whitespace
As mentioned in the reference answer on "Invisible stray Unicode" (such as a non-breaking space), you might also see this error for unsuspecting code like:
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.
See also
意外的 T_CONSTANT_ENCAPSED_STRING
意外的 T_ENCAPSED_AND_WHITESPACE
笨拙的名称
T_CONSTANT_ENCAPSED_STRING
和T_ENCAPSED_AND_WHITESPACE
引用引用的“string”
文字。它们在不同的上下文中使用,但语法问题非常相似。 T_ENCAPSED... 警告出现在双引号字符串上下文中,而 T_CONSTANT... 字符串通常在纯 PHP 表达式或语句中误入歧途。
变量插值不正确
最常见的情况是错误的 PHP 变量插值:
<前><代码> ⇓ ⇓
echo "这里出现了 $wrong['array'] 访问";
在 PHP 上下文中引用数组键是必须的。但在双引号字符串(或 HEREDOC)中这是一个错误。解析器抱怨包含的单引号
'string'
,因为它通常需要一个文字标识符/键。更准确地说,使用 PHP2 风格的简单语法是有效的双引号内用于数组引用:
但是,嵌套数组或更深层的对象引用需要 复杂的卷曲字符串表达式语法:
如果不确定,这通常使用起来更安全。它通常甚至被认为更具可读性。更好的 IDE 实际上为此使用不同的语法着色。
缺少串联
如果表达式后面有一个字符串,但缺少连接或其他运算符,那么您会看到 PHP 抱怨字符串文字:
<前><代码> ⇓
打印“你好”。世界 ” !”;
虽然这对你我来说都是显而易见的,但 PHP 无法猜测该字符串是要附加到那里的。
令人困惑的字符串引号括起来
当混淆字符串分隔符时,会发生相同的语法错误。以单
'
或双"
引号开头的字符串也以相同的结尾。<前><代码> ⇓
打印“点击此处";
⌞⎽⎽⎽⎽⎽⎽⎽⎽⌟⌞⎽⎽⎽⎽⎽⎽⎽⎽⎽ ⎽⎽⌟⌞⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⌟
该示例以双引号开头。但双引号也注定用于 HTML 属性。然而,其中预期的串联运算符被解释为单引号中的第二个字符串的一部分。
<块引用>
提示:将编辑器/IDE 设置为对单引号和双引号字符串使用稍微不同的着色。 (它还有助于应用程序逻辑更喜欢双引号字符串用于文本输出,单引号字符串仅用于类似常量的值。)
这是一个很好的例子,您首先不应该打破双引号。相反,只需使用 正确的
\"< /code> 对 HTML 属性的引号进行转义
:
虽然这也可能导致语法混乱,但所有更好的 IDE/编辑器都会通过对转义引号进行不同的着色来提供帮助。
进行不同的着色来提供帮助。缺少开头引号
相当于忘记打开
"< /code>/
'
引用解析器错误的秘诀:
<前><代码> ⇓
make_url(登录', '打开');
这里
', '
将成为裸字后面的字符串文字,而显然login
是一个字符串参数。数组列表
。
如果在数组创建块中错过了
,
逗号,解析器将看到两个连续的字符串:<前><代码>数组( ⇓
“钥匙”=> “价值”
“下一个”=> “……”,
);
请注意,最后一行可能总是包含一个额外的逗号,但忽略中间的一个逗号是不可原谅的。如果没有语法突出显示,很难发现这一点。
函数参数列表
同样的事情对于函数调用:
<前><代码> ⇓
myfunc(123, "文本", "和" "更多")
失控字符串
一个常见的变体是很简单地忘记了字符串终止符:
<前><代码> ⇓
mysql_evil("从东西中选择*);
打印“‘好的’”;
⇑
这里 PHP 抱怨两个字符串直接相邻。但真正的原因当然是未闭合的前一个字符串。
HEREDOC 缩进
之前的PHP 7.3,heredoc 字符串 结束分隔符不能以空格作为前缀:
解决方案:升级 PHP 或寻找更好的托管服务商。
另请参阅
Unexpected T_CONSTANT_ENCAPSED_STRING
Unexpected T_ENCAPSED_AND_WHITESPACE
The unwieldy names
T_CONSTANT_ENCAPSED_STRING
andT_ENCAPSED_AND_WHITESPACE
refer to quoted"string"
literals.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.
Incorrect variable interpolation
And it comes up most frequently for incorrect PHP variable interpolation:
Quoting arrays keys is a must in PHP context. But in double quoted strings (or HEREDOCs) this is a mistake. The parser complains about the contained single quoted
'string'
, because it usually expects a literal identifier / key there.More precisely it's valid to use PHP2-style simple syntax within double quotes for array references:
Nested arrays or deeper object references however require the complex curly string expression 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:
While it's obvious to you and me, PHP just can't guess that the string was meant to be appended there.
Confusing string quote enclosures
The same syntax error occurs when confounding string delimiters. A string started by a single
'
or double"
quote also ends with the same.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.
This is a good example where you shouldn't break out of double quotes in the first place. Instead just use proper
\"
escapes for the HTML attributes´ quotes:While this can also lead to syntax confusion, all better IDEs/editors again help by colorizing the escaped quotes differently.
Missing opening quote
Equivalently are forgotten opening
"
/'
quotes a recipe for parser errors: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: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:
Runaway strings
A common variation are quite simply forgotten string terminators:
Here PHP complains about two string literals directly following each other. But the real cause is the unclosed previous string of course.
HEREDOC indentation
Prior PHP 7.3, the heredoc string end delimiter can't be prefixed with spaces:
Solution: upgrade PHP or find a better hoster.
See also
意外的 T_STRING
T_STRING
有点用词不当。它不引用带引号的“string”
。这意味着遇到了原始标识符。其范围可以从裸
单词到剩余的CONSTANT
或函数名称、忘记的不带引号的字符串或任何纯文本。错误引用的字符串
但是,对于错误引用的字符串值,此语法错误最常见。任何未转义的杂散
"
或'
引号都将形成无效表达式:<前><代码> ⇓ ⇓
echo "单击此处";
语法高亮将使此类错误变得非常明显。重要的是要记住使用反斜杠来转义
\"
双引号或\'
单引号 - 取决于用作 字符串封装。"
双引号。echo
/print
行,而不是转义进出。最好考虑 HEREDOC 部分。另一个例子是在 PHP 生成的 HTML 代码中使用 PHP 条目:
如果
$text
很大且有很多行,并且开发人员看不到整个 PHP 变量值并专注于代码段而忘记了其源代码,则会发生这种情况。示例如下此处另请参阅PHP 中单引号和双引号字符串有什么区别?。
未封闭的字符串
。
如果您错过结束
"
那么语法错误通常会在稍后出现。未终止的字符串通常会消耗一些代码,直到下一个预期的字符串值:<前><代码> ⇓
echo "一些文本", $a_variable, "和一些失控的字符串;
成功(“完成”);
⇯
解析器可能会抗议的不仅仅是文字
T_STRING
。另一个常见的变化是Unexpected '>'
不带引号的文本 HTML。非编程字符串引号
如果您从博客或网站复制并粘贴代码,有时会得到无效代码。 印刷引号不是 PHP 所期望的:
印刷/智能引号是 Unicode 符号。 PHP 将它们视为相邻字母数字文本的一部分。例如
”这些
被解释为常量标识符。但是任何后续文本文字都会被解析器视为裸字/T_STRING。缺少分号;再次
如果前面的行中有未终止的表达式,则以下任何语句或语言构造都会被视为原始标识符:
<前><代码> ⇓
函数1()
函数2();
PHP 只是无法知道您是否打算依次运行两个函数,或者您是否打算将它们的结果相乘、相加、比较,或者仅运行一个
||
或另一个.PHP 脚本中的短开放标记和
标头
这种情况相当罕见。但是,如果启用了short_open_tags,则无法开始PHP脚本 带有 XML 声明:
<前><代码> ⇓
PHP 将看到
并自行回收它。它不会理解杂散的
xml
的含义。它将被解释为常量。但是版本将被视为另一个文字/常量。由于解析器无法理解两个后续文字/值之间没有表达式运算符,因此这将是解析器失败。不可见的 Unicode 字符
语法错误最可怕的原因是 Unicode 符号,例如 不间断空格< /a>. PHP 允许 Unicode 字符作为标识符名称。如果您因完全不可疑的代码而收到 T_STRING 解析器投诉,例如:
<前><代码>
您需要打开另一个文本编辑器。甚至是十六进制编辑器。这里看起来像普通的空格和换行符,可能包含不可见的常量。基于 Java 的 IDE 有时会忽略内部损坏的 UTF-8 BOM、零宽度空格、段落分隔符等。尝试重新编辑所有内容,删除空格并重新添加正常空格。
您可以通过在每行开头添加冗余
;
语句分隔符来缩小范围:<前><代码>
这里额外的
;
分号会将前面的不可见字符转换为未定义的常量引用(表达式作为语句)。作为回报,PHP 会生成一个有用的通知。变量名称前面缺少“$”符号
PHP 中的变量 由美元符号表示,后跟变量的名称。
美元符号 (
$
) 是一个印记 将标识符标记为变量的名称。如果没有此印记,标识符可能是 语言关键字 或 常量。当 PHP 代码从用另一种语言编写的代码“翻译”(C、Java 、JavaScript 等)。在这种情况下,变量类型的声明(当原始代码是用使用类型化变量的语言编写的)也可能会溜走并产生此错误。
转义引号
如果在字符串中使用
\
,则它具有特殊含义。这称为“转义字符”,通常告诉解析器按字面意思取下一个字符。示例:
echo 'Jim said \'Hello\'';
将打印Jim said 'hello'
如果转义字符串的结束引号,则结束引号将按字面意思而不是按预期理解,即作为字符串的一部分的可打印引号,而不是结束字符串。在您打开下一个字符串或在脚本末尾时,这通常会显示为解析错误。
在 Windows 中指定路径时非常常见的错误:
“C:\xampp\htdocs\”
是错误的。您需要“C:\\xampp\\htdocs\\”
。类型属性
您需要 PHP ≥7.4 才能使用属性类型,例如:
Unexpected 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 frombare
words to leftoverCONSTANT
or function names, forgotten unquoted strings, or any plain text.Misquoted strings
This syntax error is most common for misquoted string values however. Any unescaped and stray
"
or'
quote will form an invalid expression: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."
double quotes.echo
/print
lines instead of escaping in and out. Better yet consider a HEREDOC section.Another example is using PHP entry inside HTML code generated with PHP:
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: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 paste code from a blog or website, you sometimes end up with invalid code. Typographic quotes aren't what PHP expects:
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:
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:
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:
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:The extra
;
semicolon here will convert the preceding invisible character into an undefined constant reference (expression as statement). Which in return makes PHP produce a helpful notice.The `$` sign missing in front of variable names
Variables in PHP are represented by a dollar sign followed by the name of the variable.
The dollar sign (
$
) is a sigil that marks the identifier as a name of a variable. Without this sigil, the identifier could be a language keyword or a constant.This is a common error when the PHP code was "translated" from code written in another language (C, Java, JavaScript, etc.). In such cases, a declaration of the variable type (when the original code was written in a language that uses typed variables) could also sneak out and produce this error.
Escaped Quotation marks
If you use
\
in a string, it has a special meaning. This is called an "Escape Character" and normally tells the parser to take the next character literally.Example:
echo 'Jim said \'Hello\'';
will 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\\"
.Typed properties
You need PHP ≥7.4 to use property typing such as:
意外的
(
左括号通常遵循以下语言结构,例如
if
/foreach
/for
/array/
list
或在"strings"
、前面的()
、单独的之后开始语法不正确。 >$
,以及一些典型的声明函数
此错误的罕见情况是尝试使用表达式作为默认函数参数。即使在 PHP7 中,也不支持此功能:
函数声明中的参数只能是文字值或常量表达式。与函数调用不同的是,您可以自由使用
whatever(1+something()*2)
等。类属性默认值
对于类成员声明也是如此,仅允许使用文字/常量值,但不允许使用表达式:
把这样的东西放在构造函数中。
另请参阅为什么 PHP 属性不允许使用函数?
再次注意,PHP 7 只允许使用
var $xy = 1 + 2 +3;
常量表达式。PHP 中的 JavaScript 语法
使用 JavaScript 或 jQuery 语法 不起作用在 PHP 中,原因显而易见:
<前><代码>
发生这种情况时,通常表示前面有一个未终止的字符串;和文字
部分泄漏到 PHP 代码上下文中。
isset(())、空、键、下一个、当前
isset()
和empty()
都是语言内置函数,而不是函数。他们需要直接访问变量< /a>.如果您无意中添加了过多的括号,那么您将创建一个表达式:<前><代码> ⇓
if (isset(($_GET["id"]))) {
这同样适用于任何需要隐式变量名称访问的语言构造。这些内置函数是语言语法的一部分,因此不允许装饰性的额外括号。
需要变量引用但获得传递的表达式结果的用户级函数会导致运行时错误。
意外
)
缺少函数参数
函数调用中不能有逗号最后。 PHP 期望那里有一个值,因此抱怨过早关闭
)
括号。<前><代码> ⇓
callfunc(1, 2, );
仅在
array()
或list()
结构中允许使用尾随逗号。未完成的表达式
如果您忘记算术表达式中的某些内容,解析器就会放弃。因为它应该如何解释:
<前><代码> ⇓
$var = 2 * (1 + );
如果您甚至忘记了结束
)
,那么您会收到有关意外分号的投诉。Foreach 作为
常量
对于 忘记的变量
$
前缀控制语句你会看到:<前><代码> ↓ ⇓
foreach ($array 错误) {
PHP 有时会告诉您它需要
::
。因为 class::$variable 可以满足预期的 $variable 表达式..意外的
{
大括号
{
和}
将代码括起来块。它们的语法错误通常表明存在一些不正确的嵌套。if
中不匹配的子表达式最常见的不平衡
(
和)< /code>
是解析器抱怨开头卷曲
{
出现得太早的原因。一个简单的例子:<前><代码> ⇓
if (($x == $y) && (2 == true) {
计算括号的数量或使用有助于此的 IDE。另外,不要编写没有空格的代码。可读性很重要。
{ 和 }
不能在表达式中使用花括号。如果你混淆了括号和花括号,它将不符合语言语法:
<前><代码> ⇓
$var = 5 * {7 + $x};
标识符构造有一些例外,例如局部作用域变量
${references}
。可变变量或卷曲 var 表达式
这种情况非常罕见。但您也可能会收到
{
和}
解析器对复杂变量表达式的抱怨:<前><代码> ⇓
打印“你好{$world[2{]}!”;
尽管在这种情况下出现意外
}
的可能性较高。意外的
}
当收到“意外的
}
”错误时,您大多太早关闭了代码块。代码块中的最后一条语句
任何未终止的表达式都可能发生这种情况。
如果函数/代码块中的最后一行缺少尾随
;
分号:这里解析器无法判断您是否仍想将
+ 25;
添加到函数结果或其他内容中。无效的块嵌套/忘记
{
当代码块
}
过早关闭,或者您忘记了打开的{
时,您有时会看到此解析器错误:在上面的代码片段中,
if
没有左{
大括号。因此下面的结束}
就变得多余了。因此,用于该函数的下一个结束}
与原始的开始{
大括号无关。如果没有正确的代码缩进,这样的错误就更难发现。使用 IDE 和括号匹配。
意外的
{
,需要(
需要条件/声明标头和代码块的语言构造将触发此错误。
参数列表
例如,不允许错误声明没有参数列表的函数:
<前><代码> ⇓
函数无论什么{
}
控制语句条件
同样,您也不能有一个没有条件的
if
。 p><前><代码> ⇓
如果 {
}
这显然没有意义。对于常见的嫌疑人来说也是如此,
for
/foreach
、while
/do
等。<块引用>
如果您遇到此特定错误,您绝对应该查找一些手动示例。
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.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:
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:
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:
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: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.
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.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:
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:PHP here sometimes tells you it expected a
::
instead. Because a class::$variable could have satisfied the expected $variable expression..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: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:
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:Though there's a higher likelihood for an unexpected
}
in such contexts.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: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: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.
Unexpected
{
, expecting(
Language constructs which require a condition/declaration header and a code block will trigger this error.
Parameter lists
For example misdeclared functions without parameter list are not permitted:
Control statement conditions
And you can't likewise have an
if
without condition.Which doesn't make sense, obviously. The same thing for the usual suspects,
for
/foreach
,while
/do
, etc.意外的 T_IF
意外的 T_ELSEIF
意外的 T_ELSE
意外的 T_ENDIF
条件控制块
if
、elseif
和else
遵循简单的结构。当您遇到语法错误时,很可能只是无效的块嵌套 → 缺少{
大括号}
- 或者太多。由于缩进不正确而缺少
{
或}
不匹配的代码大括号对于格式不太好的代码很常见,例如:
如果您的代码如下所示,请重新开始!否则,您或其他任何人都无法修复它。在互联网上展示此内容来寻求帮助是没有意义的。
只有当您能够直观地了解 if/else 条件及其
{
代码块}
的嵌套结构和关系时,您才能修复它。使用您的 IDE 查看它们是否全部配对。<前><代码>如果(真){
如果(假){
……
}
elseif ($随便) {
如果($某事2){
……
}
别的 {
……
}
}
别的 {
……
}
if (false) { // 第二个 `if` 树
……
}
别的 {
……
}
}
elseif(假){
……
}
任何双
}
}
不仅会关闭分支,还会关闭先前的条件结构。因此,坚持使用一种编码风格;不要在嵌套的 if/else 树中混合和匹配。除了这里的一致性之外,事实证明它也有助于避免冗长的条件。使用临时变量或函数以避免不可读的
if
表达式。IF
不能在表达式中使用新手经常犯的一个令人惊讶的错误是尝试在表达式中使用
if
语句,例如 print 语句:<前><代码> ⇓
回显“”;
否则会破坏此类输出结构:使用多个
ifs 和
echo
s。
更好的是,使用临时变量,并将条件放在之前:< /p>
为这种情况定义函数或方法通常也是有意义的。
控制块不返回“结果”
现在这种情况不太常见,但一些程序员甚至尝试将
if
视为可以返回结果:其结构与在字符串连接/表达式中使用
if
相同。您必须在代码块中使用赋值:
或者,采用
?:
三元比较。如果在如果
您不能嵌套
if
< /a> 在以下条件之一内:<前><代码> ⇓
if ($x == true and (if $y != false)) { ... }
这显然是多余的,因为
and
(或or
)已经允许链接比较。忘记
;
分号再说一遍:每个控制块都需要是一个语句。如果前面的代码片段不是以分号结尾,那么这肯定是一个语法错误:
<前><代码> ⇓
$var = 1 + 2 + 3
如果(真){ … }
顺便说一句,
{…}
代码块中的最后一行也需要一个分号。分号太早
现在责怪特定的编码风格可能是错误的,因为这个陷阱太容易被忽视:
<前><代码> ⇓
如果($x==5);
{
$y = 7;
}
否则←
{
$x = -1;
}
这种情况发生的频率比您想象的要高。
终止
它将执行一个void语句。if ()
表达式时;;
变成了自己的空{}
!{…}
块因此与if
分离,并且始终运行。else
不再与开放的if
构造相关,这就是为什么这会导致意外的 T_ELSE 语法错误。
这也解释了这个语法错误的同样微妙的变化:
代码块
{…}
之后的;
终止整个if
构造,在语法上切断
else
分支。不使用代码块
语法上允许在
if
/elseif
/< 中的代码块省略大括号{
...}
代码>其他分支。遗憾的是,对于不熟悉的程序员来说,这是一种非常常见的语法风格。 (在错误的假设下,打字或阅读速度更快)。然而,这很可能会导致语法错误。迟早会有其他语句进入 if/else 分支:
<前><代码>如果(真)
$x = 5;
elseif(假)
$x = 6;
$y = 7; ←
别的
$z = 0;
但要实际使用代码块,您必须这样编写
{
...}
!<块引用>
即使是经验丰富的程序员也会避免这种无括号语法,或者至少
将其理解为规则的例外。
Else / Elseif 顺序错误
当然,要提醒自己的一件事是条件顺序。
您可以拥有任意数量的
elseif
,但是else
必须放在最后。事情就是这样。类声明
正如上面提到的,类声明中不能有控制语句:
您忘记了一个函数 定义,或者在这种情况下过早关闭一个
}
。意外的 T_ELSEIF / T_ELSE
混合 PHP 和 HTML 时,
if/elseif
的结束}
必须位于同一 PHP 块中code> 作为下一个
elseif/else
。这将生成错误,因为if
的结束}
需要成为elseif
的一部分:正确的形式
:
这或多或少是不正确缩进的一种变体 - 大概通常基于错误的编码意图。
您不能混搭其他语句
if
和elseif
/else
结构标记之间:<前><代码>如果(真){
}
回声“在两者之间”; ←
elseif(假){
}
?>文本
两者只能出现在
{…}
代码块中,而不能出现在控制结构标记之间。if
和else
分支之间跳转时,并不存在某种“未定义”状态。您也不能在不同的控制结构之间分隔 if/else:
if
和之间没有语法关系否则。
foreach
词法作用域以}
结束,因此if
结构没有必要继续下去。T_ENDIF
如果抱怨意外的 T_ENDIF,则说明您正在使用替代语法样式
if:
⋯elseif:
⋯else:
⋯ <代码>endif;。你真的应该三思而后行。一个常见的陷阱是令人毛骨悚然的类似
:
冒号代表;
分号。 (包含在“分号太早”中)由于模板文件中的缩进更难跟踪,因此使用替代语法时缩进更难 - 您的
endif;
可能与任何if:
不匹配。使用
} endif;< /代码>
是一个双
if
终止符。虽然“意外的 $end”通常是忘记结束
}
大括号的代价。赋值与比较
所以,这不是语法错误,但在这种情况下值得一提:
<前><代码> ⇓
如果 ($x = true) { }
否则 { do_false(); }
这不是
==
/=== 比较,但是
=
赋值。这是相当微妙的,很容易导致一些用户无助地编辑整个条件块。首先要注意意外的赋值 - 当您遇到逻辑错误/不当行为时。
Unexpected T_IF
Unexpected T_ELSEIF
Unexpected T_ELSE
Unexpected T_ENDIF
Conditional control blocks
if
,elseif
andelse
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.Missing
{
or}
due to incorrect indentationMismatched code braces are common to less well-formatted code such as:
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.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:Which is invalid of course.
You can use a ternary conditional, but beware of readability impacts.
Otherwise break such output constructs up: use multiple
if
s andecho
s.Better yet, use temporary variables, and place your conditionals before:
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:Which is structurally identical to using
if
within a string concatenation / expression.You'll have to use an assignment in the code block:
Alternatively, resort to a
?:
ternary comparison.If in If
You cannot nest an
if
within a condition either: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:
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:
Which happens more often than you might imagine.
if ()
expression with;
it will execute a void statement. The;
becomes a an empty{}
of its own!{…}
block thus is detached from theif
, and would always run.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:
Where the
;
after the code block{…}
terminates the wholeif
construct, severing the
else
branch syntactically.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:
But to actually use code blocks, you do have to write
{
…}
them as such!Else / Elseif in wrong order
One thing to remind yourself is the conditional order, of course.
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:
You either forgot a function definition, or closed one
}
too early in such cases.Unexpected T_ELSEIF / T_ELSE
When mixing PHP and HTML, the closing
}
for 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
:The correct form
<?php } elseif
:This is more or less a variation of incorrect indentation - presumably often based on wrong coding intentions.
You cannot mash other statements inbetween
if
andelseif
/else
structural tokens:Either can only occur in
{…}
code blocks, not in between control structure tokens.if
andelse
branches.Nor can you part an if/else between different control structures:
There is no syntactic relation between the
if
andelse
. Theforeach
lexical scope ends at}
, so there's no point for theif
structure to continue.T_ENDIF
If an unexpected T_ENDIF is complained about, you're using the alternative syntax style
if:
⋯elseif:
⋯else:
⋯endif;
. Which you should really think twice about.A common pitfall is confusing the eerily similar
:
colon for a;
semicolon. (Covered in "Semicolon too early")As indentation is harder to track in template files, the more when using the alternative syntax - it's plausible your
endif;
does not match anyif:
.Using
} endif;
is a doubled
if
-terminator.While an "unexpected $end" is usually the price for a forgotten closing
}
curly brace.Assignment vs. comparison
So, this is not a syntax error, but worth mentioning in this context:
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.意外的 $end
当 PHP 谈论“意外的
$end
”时,这意味着您的代码在解析器等待更多代码时结束。 (从字面上看,该消息有点误导。它与新手有时假设的名为“$end”的变量无关。它指的是“文件结尾”,EOF。)几乎总是缺少
}
大括号来关闭前面的代码块。它的意思是,解析器期望找到结束}
但实际上到达了文件末尾。再次强调,使用适当的缩进以避免此类问题。
使用带有括号匹配的 IDE,找出
}
的错误位置。大多数 IDE 和文本编辑器中都有键盘快捷键:
大多数 IDE 还突出显示匹配的大括号、方括号和圆括号。
这使得检查它们的相关性变得非常容易:
未终止的表达式
意外的 $end 未终止的表达式或语句也可能发生语法/解析器错误:
$var = func(1,
?>
EOF因此,首先查看脚本的末尾。对于任何 PHP 脚本中的最后一个语句来说,尾随的
;
通常都是多余的。但你应该拥有一个。正是因为它缩小了此类语法问题的范围。特别是当您发现自己在脚本末尾添加了更多语句之后。缩进的 HEREDOC 标记
另一种常见情况是 HEREDOC 或NOWDOC 字符串。带有前导空格、制表符等的终止标记将被忽略:
因此解析器假定 HEREDOC 字符串继续直到文件末尾(因此“意外的 $end”)。几乎所有 IDE 和语法高亮编辑器都会使这一点变得明显或发出警告。
转义引号
如果在字符串中使用
\
,则它具有特殊含义。这称为“转义字符”,通常告诉解析器从字面上看下一个字符。示例:
echo 'Jim said \'Hello\'';
将打印Jim said 'hello'
如果对字符串的结束引号进行转义,则将采用结束引号从字面上看,并不像预期的那样,即作为可打印的引号作为字符串的一部分,而不是关闭字符串。在打开下一个字符串或在脚本末尾时,这通常会显示为解析错误。
在 Windows 中指定路径时非常常见的错误:
"C:\xampp\htdocs\"
是错误的。您需要“C:\\xampp\\htdocs\\”
。或者,PHP 通常会将 Unix 样式路径(例如"C:/xampp/htdocs/"
)转换为 Windows 的正确路径。替代语法
在模板中使用语句/代码块的替代语法时,很少会看到此语法错误。例如,使用
if:
和else:
以及缺少的endif;
。另请参阅:
Unexpected $end
When PHP talks about an "unexpected
$end
", it means that your code ended while the parser is expecting more code. (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.)It's pretty much always about a missing
}
curly brace to close preceding code blocks. What it's saying is that the parser is expecting to find a closing}
but actually reached the end of the file.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:
Most IDEs also highlight matching braces, brackets and parentheses.
Which makes it pretty easy to inspect their correlation:
Unterminated expressions
An
Unexpected $end
syntax/parser error can also occur for unterminated expressions or statements:$var = func(1,
?>
EOFSo, look at the end of scripts first. A trailing
;
is often redundant for the last statement in any PHP script. But you should have one. Precisely because it narrows such syntax issues down. Particularly after you find yourself adding more statements at the end of the script.Indented HEREDOC markers
Another common occurrence appears with HEREDOC or NOWDOC strings. The terminating marker goes ignored with leading spaces, tabs, etc.:
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.
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 specifying paths in Windows:
"C:\xampp\htdocs\"
is wrong. You need"C:\\xampp\\htdocs\\"
. Alternately, PHP will usually convert Unix-style paths (e.g."C:/xampp/htdocs/"
) to the correct path for Windows.Alternative syntax
Somewhat rarer you can see this syntax error when using the alternative syntax for statement/code blocks in templates. Using
if:
andelse:
and a missingendif;
for example.See also:
意外的 T_IS_EQUAL
意外 T_IS_GREATER_OR_EQUAL
意外的 T_IS_IDENTICAL
意外的 T_IS_NOT_EQUAL
意外的 T_IS_NOT_IDENTICAL
意外的 T_IS_SMALLER_OR_EQUAL
意外的
<
意外的
>
比较运算符,例如
==
、>=
、===
、!=
、< ;>
、!==
和<=
或<
和>
大部分应该仅在表达式中使用,例如if
表达式。如果解析器抱怨它们,那么通常意味着它们周围的配对不正确或不匹配(
)
括号。括号分组
特别是对于具有多重比较的
if
语句,您必须注意正确计数左括号和右括号:<前><代码> ⇓
if (($foo < 7) && $bar) > 5 || $baz < 9) { ... }
↑
此处的
if
条件已被) 终止
一旦您的比较变得足够复杂,通常有助于将其拆分为多个嵌套的
if
结构。isset() 与比较混合
一个常见的新手是尝试结合
isset()
或 < a href="http://php.net/empty" rel="nofollow noreferrer">empty()
进行比较:<前><代码> ⇓
if (空($_POST["var"] == 1)) {
或者甚至:
<前><代码> ⇓
if (isset($variable !== "值")) {
这对 PHP 来说没有意义,因为
isset
和empty
是只接受变量名称的语言结构。比较结果也没有意义,因为输出只是/已经是一个布尔值。令人困惑的
>=
大于或等于=>
数组运算符两个运算符看起来有些相似,因此有时会混淆:
<前><代码> ⇓
if ($var => 5) { ... }
您只需记住该比较运算符称为“大于”或等于”即可正确计算。
另请参阅:PHP 中的 If 语句结构
没有可比较的内容
如果两个比较属于相同的变量名称,您也不能将它们组合起来:
<前><代码> ⇓
if ($xyz > 5 且 < 100)
PHP 无法推断出您打算再次比较初始变量。表达式通常根据运算符优先级进行配对,因此到了
<
可见,原始变量仅剩下一个布尔结果。另请参阅:意外的 T_IS_SMALLER_OR_EQUAL
比较链
您无法与带有一行运算符的变量进行比较:
<前><代码> ⇓
$结果 = (5 < $x < 10);
这必须分为两个比较,每个比较都针对
$x
。这实际上更多的是列入黑名单的表达式的情况(由于等效运算符关联性)。它在一些 C 风格语言中在语法上是有效的,但 PHP 也不会将其解释为预期的比较链。
意外
>
意外
<
大于
>
或小于<
运算符没有自定义T_XXX
分词器名称。虽然它们可能像其他所有东西一样被放错地方,但您更经常看到解析器抱怨它们错误引用的字符串和混杂的 HTML:<前><代码> ⇓
print " 与文字常量
Hello
进行比较,然后与另一个进行比较<
比较。或者至少 PHP 是这么认为的。实际原因和语法错误是过早的字符串"
终止。也不可能嵌套 PHP 开始标签:
另请参阅:
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
>
Comparison operators such as
==
,>=
,===
,!=
,<>
,!==
and<=
or<
and>
mostly should be used just in expressions, such asif
expressions. If the parser complains about them, then it often means incorrect paring or mismatched(
)
parens around them.Parens grouping
In particular for
if
statements with multiple comparisons you must take care to correctly count opening and closing parenthesis: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:Or even:
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:
You only need to remember that this comparison operator is called "greater than or equal" to get it right.
See also: If statement structure in PHP
Nothing to compare against
You also can't combine two comparisons if they pertain the same variable name:
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:
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: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:
See also:
意外的 T_IF
意外的 T_FOREACH
意外的 T_FOR
意外的 T_WHILE
意外的 T_DO
意外的 T_ECHO
控制结构,例如
if
、foreach
、for
、while
、list
、< code>global、return
、do
、print
、echo
只能用作语句。它们通常单独驻留在一条线上。分号;你在哪里?
如果解析器抱怨,您通常会在上一行中漏掉一个分号关于控制语句:
<前><代码> ⇓
$x = myfunc()
如果(真){
解决方案:查看上一行;添加分号。
类声明
发生这种情况的另一个位置是类声明。在类部分中,您只能列出属性初始化和方法部分。那里不能驻留任何代码。
此类语法错误通常是由于错误嵌套的
{
和}
造成的。特别是当功能代码块关闭得太早时。表达式上下文中的语句
大多数语言结构只能用作语句 。它们不应该放置在其他表达式中:
<前><代码> ⇓
$var = array(1, 2, foreach($else as $_), 5, 6);
同样,您不能在字符串、数学表达式或其他地方使用
if
:<前><代码> ⇓
打印“哦,”。如果(真){“你!” } 。 “行不通”;
// 如果足够熟悉,请在此处使用三元条件。
为了在表达式中嵌入类似于
if
的条件,您通常需要使用?:
三元评估。这同样适用于
for
、while
、global
、echo
和较小的扩展list
.<前><代码> ⇓
echo 123, echo 567, “啊?”;
而
print()
是一种可以在表达式上下文中使用的内置语言。 (但很少有意义。)保留关键字作为标识符
您也不能使用
do
或if
以及其他语言结构来表示用户定义的函数或类名。 (也许在 PHP 7 中。但即便如此,也不建议这样做。)在控制块后面有一个分号,而不是冒号 (:) 或大括号 ({)
控制结构通常用花括号括起来(但冒号可以在 替代语法)来表示其范围。如果您不小心使用了分号,则会过早地关闭该块,从而导致关闭语句抛出错误。
Unexpected T_IF
Unexpected T_FOREACH
Unexpected T_FOR
Unexpected T_WHILE
Unexpected T_DO
Unexpected T_ECHO
Control constructs such as
if
,foreach
,for
,while
,list
,global
,return
,do
,print
,echo
may only be used as statements. They usually reside on a line by themselves.Semicolon; where you at?
Pretty universally have you missed a semicolon in the previous line if the parser complains about a control statement:
Solution: look into the previous line; add semicolon.
Class declarations
Another location where this occurs is in class declarations. In the class section you can only list property initializations and method sections. No code may reside there.
Such syntax errors commonly materialize for incorrectly nested
{
and}
. In particular when function code blocks got closed too early.Statements in expression context
Most language constructs can only be used as statements. They aren't meant to be placed inside other expressions:
Likewise can't you use an
if
in strings, math expressions or elsewhere:For embedding
if
-like conditions in an expression specifically, you often want to use a?:
ternary evaluation.The same applies to
for
,while
,global
,echo
and a lesser extendlist
.Whereas
print()
is a language built-in that may be used in expression context. (But rarely makes sense.)Reserved keywords as identifiers
You also can't use
do
orif
and other language constructs for user-defined functions or class names. (Perhaps in PHP 7. But even then it wouldn't be advisable.)Your have a semi-colon instead of a colon (:) or curly bracket ({) after your control block
Control structures are typically wrapped in curly braces (but colons can be used in an alternative syntax) to represent their scope. If you accidentally use a semi-colon you prematurely close that block resulting in your closing statement throwing an error.
意外的“?”
如果您尝试在
中使用
,则会出现此错误*。
* 适用于 PHP 版本 4.3.1、4.3.5 - 4.3.11、4.4.0 - 4.4.1、5.0.0 - 5.0.5、4.4.2 - 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.0 - 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
如果您尝试在 PHP 7 之前的 PHP 版本中使用空合并运算符
??
,您将收到此错误。意外的 '?',期望变量
对于可空类型,可能会发生类似的错误,如下所示:
这再次表明正在使用过时的 PHP 版本(CLI 版本
php -v
或绑定了一个的 Web 服务器>phpinfo();
)。Unexpected '?'
If you are trying to use
<?php
within<?php
this error will be given*.* For PHP versions 4.3.1, 4.3.5 - 4.3.11, 4.4.0 - 4.4.1, 5.0.0 - 5.0.5, 4.4.2 - 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.0 - 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
If you are trying to use the null coalescing operator
??
in a version of PHP prior to PHP 7 you will get this error.Unexpected '?', expecting variable
A similar error can occur for nullable types, as in:
Which again indicates an outdated PHP version being used (either the CLI version
php -v
or the webserver bound onephpinfo();
).意外的 T_LNUMBER
标记
T_LNUMBER
指的是“长”/ 数字。无效的变量名称
在 PHP 和大多数其他编程语言中,变量 不能以数字开头。第一个字符必须是字母或下划线。
经常出现在 PHP 上下文中使用
preg_replace
-占位符"$1"
:<前><代码># ↓ ⇓ ↓
preg_replace("/#(\w+)/e", strtopupper($1) )
回调应该被引用的地方。 (现在
/e
正则表达式标志已被弃用。但它有时仍然在preg_replace_callback
函数中被误用。)相同的标识符约束适用于对象属性,顺便说一句。
<前><代码> ↓
$json->0->值
虽然分词器/解析器不允许使用文字
$1
作为变量名称,但可以使用${1}
或${"1"}
。这是非标准标识符的语法解决方法。 (最好将其视为本地范围查找。但通常:在这种情况下更喜欢纯数组!)有趣的是,但非常不推荐,PHP 解析器允许 Unicode 标识符;这样
$➊
是有效的。 (与文字1
不同)。杂散数组条目
数组声明也可能出现意外的 long - 当缺少
,
逗号时:<前><代码># ↓ ↓
$xy = 数组(1 2 3);
或者同样的函数调用和声明,以及其他构造:
func(1, 2 3);
函数 xy($z 2);
对于 ($i=2 3<$z)
因此,通常会缺少
;
或,
之一来分隔列表或表达式。错误引用的 HTML
再说一遍,错误引用的字符串是杂散的常见来源数字:
<前><代码># ↓ ↓
echo "有什么不好的";
此类情况应该或多或少像意外的 T_STRING 错误一样对待。
其他标识符
既不是函数、类,也不是命名空间 可以以数字开头命名:
<前><代码> ↓
函数 123shop() {
与变量名几乎相同。
Unexpected T_LNUMBER
The token
T_LNUMBER
refers to a "long" / number.Invalid variable names
In PHP, and most other programming languages, variables cannot start with a number. The first character must be alphabetic or an underscore.
Quite often comes up for using
preg_replace
-placeholders"$1"
in PHP context:Where the callback should have been quoted. (Now the
/e
regex flag has been deprecated. But it's sometimes still misused inpreg_replace_callback
functions.)The same identifier constraint applies to object properties, btw.
While the tokenizer/parser does not allow a literal
$1
as variable name, one could use${1}
or${"1"}
. Which is a syntactic workaround for non-standard identifiers. (It's best to think of it as a local scope lookup. But generally: prefer plain arrays for such cases!)Amusingly, but very much not recommended, PHPs parser allows Unicode-identifiers; such that
$➊
would be valid. (Unlike a literal1
).Stray array entry
An unexpected long can also occur for array declarations - when missing
,
commas:Or likewise function calls and declarations, and other constructs:
func(1, 2 3);
function xy($z 2);
for ($i=2 3<$z)
So usually there's one of
;
or,
missing for separating lists or expressions.Misquoted HTML
And again, misquoted strings are a frequent source of stray numbers:
Such cases should be treated more or less like Unexpected T_STRING errors.
Other identifiers
Neither functions, classes, nor namespaces can be named beginning with a number either:
Pretty much the same as for variable names.
意外的“=”
这可能是由于变量名称中包含无效字符造成的。变量名称必须遵循以下规则:
Unexpected '='
This can be caused by having invalid characters in a variable name. Variables names must follow these rules:
意外的“endwhile”(T_ENDWHILE)
语法使用冒号 - 如果没有冒号,则会发生上述错误。
此语法的替代方法是使用大括号:
http://php.net/手册/en/control-structs.while.php
Unexpected 'endwhile' (T_ENDWHILE)
The syntax is using a colon - if there is no colon the above error will occur.
The alternative to this syntax is using curly brackets:
http://php.net/manual/en/control-structures.while.php
意外的“。”
如果您尝试在某个对象中使用 splat 运算符(
...
),则可能会发生这种情况PHP 版本不受支持。...
首先在 PHP 5.6 中可用,用于捕获函数的可变数量的参数:在 PHP 7.4 中,您可以将它用于 数组表达式。
Unexpected '.'
This can occur if you are trying to use the splat operator(
...
) in an unsupported version of PHP....
first became available in PHP 5.6 to capture a variable number of arguments to a function:In PHP 7.4, you could use it for Array expressions.
意外的
:
1. PHP 8 命名参数语法
如果尝试在 PHP < 版本中使用 PHP 8 的新命名参数功能8. 会出现此错误:
解决方案:
2. 裁剪类
::
分隔符开头的错误消息 Parse error: 语法错误,意外的 ':' 可能是由于错误地将类静态引用
Class::$Variable
编写为类:$Variable
。Unexpected
:
1. PHP 8 named parameter syntax
If attempting to use PHP 8's new named parameter functionality in a version of PHP < 8 this error will occur:
Solutions:
2. Cropped class
::
separatorAn error message that begins Parse error: syntax error, unexpected ':' can be caused by mistakenly writing a class static reference
Class::$Variable
asClass:$Variable
.意外的“继续”(T_CONTINUE)
continue
是一个语句(如 for 或 if),并且必须独立出现。它不能用作表达式的一部分。部分原因是 continue 不返回值,但在表达式中,每个子表达式都必须产生某个值,因此整个表达式都会产生一个值。这就是语句和表达式之间的区别。这意味着 continue 不能用在三元语句或任何需要返回值的语句中。
意外的“中断”(T_BREAK)
当然,
break;
也是如此。它也不能在表达式上下文中使用,而是一个严格的语句(与foreach
或if
块处于同一级别)。意外的“返回”(T_RETURN)
现在,这对于
return
来说可能更令人惊讶,但这也只是一个块级语句。它确实向更高的作用域/函数返回一个值(或 NULL),但它并不将其计算为表达式本身。 → 也就是说:执行return(return(false);;
是没有意义的Unexpected 'continue' (T_CONTINUE)
continue
is a statement (like for, or if) and must appear standalone. It cannot be used as part of an expression. Partly because continue doesn't return a value, but in an expression every sub-expression must result in some value so the overall expression results in a value. That's the difference between a statement and an expression.That means
continue
cannot be used in a ternary statement or any statement that requires a return value.Unexpected 'break' (T_BREAK)
Same goes for
break;
of course. It's also not usable in expression context, but a strict statement (on the same level asforeach
or anif
block).Unexpected 'return' (T_RETURN)
Now this might be more surprising for
return
, but that's also just a block-level statement. It does return a value (or NULL) to the higher scope/function, but it does not evaluate as expression itself. → That is: there's no point in doingreturn(return(false);;
发生这些错误的另一个原因是意外的空格,例如代码中的类似字符,代码行似乎很完美,但它们包含一些类似于换行符、空格或制表符的特定字符,但它们不会被代码解析解析器。
当我尝试通过简单地复制粘贴将一些代码从网页放入代码编辑器时,我遇到了这个问题,我在数组定义中看到了这个错误。数组定义中的一切看起来都正确。我无法解决正确的错误,最后我在单行中定义了这个数组,然后错误就消失了。然后我再次尝试使该定义成为多个,但手动为每个数组元素添加中断(Enter)并保存文件,这次编辑器没有解析错误,运行时也没有错误。
例如,我在一个博客上遇到了这个片段的问题,实际上无法发布这些片段,因为堆栈溢出已经知道代码的问题。
然后在解决它之后,我的工作片段看起来与显示解析错误
语法错误,意外的“auth”(T_CONSTANT_ENCAPSED_STRING),期待“]”的片段类似
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.
then after solving it my working snippet is, which looks similar with one which shows parsing error
syntax error, unexpected ''auth'' (T_CONSTANT_ENCAPSED_STRING), expecting ']'