问题:PHP解析/语法错误;以及如何解决它们

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

PHP解析错误:语法错误,第20行的index.php中出现意外的'{'

意外的符号并不总是真正的罪魁祸首。但是行号给出了从哪里开始寻找的粗略思路。

始终查看代码上下文。语法错误通常隐藏在以前的代码行中提到的中。将代码与手册中的语法示例进行比较。

虽然并非每种情况都匹配。但是,还有一些 解决语法错误 的一般步骤。这些参考文献总结了常见的陷阱:

密切相关的参考文献:

并且:

虽然Stack Overflow也欢迎菜鸟编码人员,但它主要针对专业编程问题。

  • 回答每个人的编码错误和狭窄的拼写错误通常被认为是题外话。
  • 因此,在发布语法修复请求之前,请花些时间遵循基本步骤
  • 如果仍然需要,请展示自己的解决方案,尝试的解决方案以及您对外观或问题的思考过程。

如果您的浏览器显示错误消息,例如" SyntaxError:非法字符",则实际上不是相关,但-语法错误


供应商代码上出现的语法错误:最后,请考虑一下,如果语法错误不是由于编辑您的代码库引起的,而是在安装或升级了外部供应商软件包之后,则可能是由于PHP版本引起的不兼容,因此请根据您的平台设置检查供应商的要求。

标签:php,parsing,debugging,syntax-error

Q: PHP parse/syntax errors; and how to solve them

Everyone runs into syntax errors. Even experienced programmers make typos. For newcomers, it's just part of the learning process. However, it's often easy to interpret error messages such as:

PHP Parse error: syntax error, unexpected '{' in index.php on line 20

The unexpected symbol isn't always the real culprit. But the line number gives a rough idea of where to start looking.

Always look at the code context. The syntax mistake often hides in the mentioned or in previous code lines. Compare your code against syntax examples from the manual.

While not every case matches the other. Yet there are some general steps to solve syntax mistakes. This references summarized the common pitfalls:

Closely related references:

And:

While Stack Overflow is also welcoming rookie coders, it's mostly targetted at professional programming questions.

  • 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 browser displays error messages such as "SyntaxError: illegal character", then it's not actually -related, but a -syntax error.


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.

回答1:

语法错误是什么?

PHP属于 C风格命令式编程语言。它具有严格的语法规则,遇到错位的符号或标识符时无法恢复。它无法猜测您的编码意图。

最重要的提示

您始终可以采取一些基本的预防措施:

  • 使用适当的代码缩进,或采用任何高级编码样式。可读性可防止出现违规情况。

  • 使用 IDE 或编辑器用于PHP 并带有突出显示语法。这也有助于括号/括号的平衡。

  • 阅读手册中的语言参考和示例。两次,变得精通。

如何解释解析器错误

典型的语法错误消息为:

解析错误:语法错误,意外的 T_STRING ,在 file.php 中的';' strong> line 217

其中列出了语法错误的可能位置。请参阅提到的文件名行号

诸如T_STRING之类的名称解释了解析器/令牌无法识别的符号最后处理。但是,这不一定是语法错误的原因。

同样重要的是要查看以前的代码行。通常,语法错误只是更早发生的不幸。错误行号正是解析器最终放弃处理所有错误的地方。

解决语法错误

有许多方法可以缩小和修复语法错误。

  • 打开提到的源文件。查看提到的代码行

    • 对于失控的字符串和放错位置的运算符,通常会在这里找到罪魁祸首。

    • 从左到右阅读该行,并想象每个符号的作用。

  • 更经常地,您还需要查看前几行

    • 尤其是,缺少的;分号在前一行的末尾/语句中丢失。 (至少从样式角度来看。)

    • 如果{代码块}被错误地关闭或嵌套,则可能需要进一步研究源代码。使用适当的代码缩进可以简化这一过程。

  • 查看语法着色

    • 字符串,变量和常量都应具有不同的颜色。

    • 运算符+-*/.也应设置为不同的颜色。否则它们可能处于错误的上下文中。

    • 如果您看到字符串着色延伸得太远或太短,则您发现了一个未转义或缺少的"'字符串标记。

    • 彼此相邻的两个相同颜色的标点符号也可能带来麻烦。通常,如果不是++-或运算符后的括号,运算符将是孤独的。在大多数情况下,紧随其后的两个字符串/标识符是错误的。

  • 空白是您的朋友。遵循 any 编码样式。

  • 暂时中断长行。

    • 您可以在运算符或常量和字符串之间自由地添加换行符。解析器然后将具体化行号以解析错误。您可以查看丢失或放错位置的语法符号,而不必查看冗长的代码。

    • 将复杂的if语句拆分为不同的或嵌套的if条件。

    • 使用临时变量来简化代码,而不是使用冗长的数学公式或逻辑链。 (更具可读性=更少错误。)

    • 在之间添加换行符:

      1. 您可以轻松将其识别为正确的代码
      2. 您不确定的部分,
      3. 解析器抱怨的行。

      对长代码块进行分区确实有助于查找语法错误的起源。

  • 注释掉违规代码。

    • 如果您不能找出问题根源,请开始注释掉(并因此暂时删除)代码块。

    • 摆脱解析错误后,您便找到了问题根源。在那里仔细看。

    • 有时您想暂时删除完整的功能/方法块。 (如果花括号不匹配且代码缩进不正确。)

    • 当您无法解决语法问题时,请尝试重写从头开始注释掉的部分

  • 作为新手,请避免使用一些令人困惑的语法构造。

    • 三元组?:条件运算符可以压缩代码,并且确实有用。但这并不能在所有情况下都有助于可读性。最好不要使用普通的if语句。

    • PHP的替代语法(if: / elseif: / endif;)在模板中很常见,但可以说不那么容易比正常的{ code }块遵循。

  • 最常见的新人错误是:

    • 缺少分号;来终止语句/行。

    • "'的字符串引号不匹配,并且其中的未转义引号。

    • 被遗忘的运算符,尤其是字符串.串联。

    • 不平衡的(括号)。在报告的行中计数它们。它们是否相等?

  • 别忘了解决一个语法问题可以发现下一个语法问题。

    • 如果您解决了一个问题,但在下面的某些代码中发现了其他问题,那么您通常走在正确的道路上。

    • 如果在编辑新的语法错误后又出现在同一行中,则您尝试的更改可能是失败的。 (并非总是如此。)

  • 如果无法修复,请还原以前工作的代码的备份。

    • 采用源代码版本控制系统。您始终可以查看损坏的最新版本的diff。关于语法问题,这可能会有所启发。
  • 不可见的Unicode杂散字符:在某些情况下,您需要在您的来源上使用hexeditor 或其他编辑器/查看器。仅仅通过查看代码就无法发现某些问题。

  • 请注意文件中保存了哪种换行符类型

    • PHP仅接受 \ n 换行符,而不接受 \ r 回车符。

    • 对于MacOS用户来说,这有时是个问题(即使在OS X上,配置错误的编辑器也是如此)。

    • 通常仅在使用单行//#注释时才会出现此问题。当换行符被忽略时,多行/*...*/注释很少会干扰解析器。

  • 如果您的语法错误未通过网络传输:可能是您的计算机上出现语法错误。但是,将相同的文件在线发布不再显示。这仅意味着两件事之一:

    • 您正在查看错误的文件!

    • 或者您的代码包含不可见的杂散Unicode(请参见上文)。您可以轻松地找到:只需将代码从Web表单复制回文本编辑器即可。

  • 检查您的 PHP版本。并非所有语法构造都可在每台服务器上使用。

    • php-v用于命令行解释器

    • 通过网络服务器调用的那个。


    这些不一定相同。特别是在使用框架时,您将使它们匹配。

  • 请勿使用 PHP的保留关键字作为函数/方法,类的标识符或常量。

  • 试错是您的最后选择。

如果其他所有方法均失败,则您始终可以 GOOGLE 您的错误消息。语法符号的搜索并非那么容易(但是堆栈溢出本身通过 SymbolHound 进行索引)。因此,可能需要先浏览几页,然后才能找到相关的内容。

更多指南:

死亡白屏

如果您的网站只是空白,则通常是语法错误。通过以下方式启用其显示:

  • error_reporting=E_ALL
  • display_errors=1

在您的 php.ini 通常,或通过 .htaccess 来获取mod_php ,甚至 .user.ini 使用FastCGI设置。

在损坏的脚本中启用它为时已晚,因为PHP甚至无法解释/运行第一行。一个快速的解决方法是制作一个包装脚本,例如test.php

<?php
   error_reporting(E_ALL);
   ini_set("display_errors", 1);
   include("./broken-script.php");

然后通过访问此包装脚本来调用失败的代码。

它还有助于启用PHP的error_log,并查看您的网络服务器的当脚本因HTTP 500响应而崩溃时,error.log

A1:

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:

Parse error: syntax error, unexpected T_STRING, expecting ';' in file.php on line 217

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 nested if conditions.

    • Instead of lengthy math formulas or logic chains, use temporary variables to simplify the code. (More readable = fewer errors.)

    • Add newlines between:

      1. The code you can easily identify as correct,
      2. The parts you're unsure about,
      3. And the lines which the parser complains about.

      Partitioning up long code blocks really helps to locate the origin of syntax errors.

  • Comment out offending code.

    • If you can't isolate the problem source, start to comment out (and thus temporarily remove) blocks of code.

    • As soon as you got rid of the parsing error, you have found the problem source. Look more closely there.

    • Sometimes you want to temporarily remove complete function/method blocks. (In case of unmatched curly braces and wrongly indented code.)

    • When you can't resolve the syntax issue, try to rewrite the commented out sections from scratch.

  • As a newcomer, avoid some of the confusing syntax constructs.

    • The ternary ? : condition operator can compact code and is useful indeed. But it doesn't aid readability in all cases. Prefer plain if statements while unversed.

    • PHP's alternative syntax (if:/elseif:/endif;) is common for templates, but arguably less easy to follow than normal { code } blocks.

  • The most prevalent newcomer mistakes are:

    • Missing semicolons ; for terminating statements/lines.

    • Mismatched string quotes for " or ' and unescaped quotes within.

    • Forgotten operators, in particular for the string . concatenation.

    • Unbalanced ( parentheses ). Count them in the reported line. Are there an equal number of them?

  • Don't forget that solving one syntax problem can uncover the next.

    • If you make one issue go away, but other crops up in some code below, you're mostly on the right path.

    • If after editing a new syntax error crops up in the same line, then your attempted change was possibly a failure. (Not always though.)

  • Restore a backup of previously working code, if you can't fix it.

    • Adopt a source code versioning system. You can always view a diff of the broken and last working version. Which might be enlightening as to what the syntax problem is.
  • Invisible stray Unicode characters: In some cases, you need to use a hexeditor or different editor/viewer on your source. Some problems cannot be found just from looking at your code.

    • Try grep --color -P -n "\[\x80-\xFF\]" file.php as the first measure to find non-ASCII symbols.

    • In particular BOMs, zero-width spaces, or non-breaking spaces, and smart quotes regularly can find their way into the source code.

  • Take care of which type of linebreaks are saved in files.

    • PHP just honors \n newlines, not \r carriage returns.

    • Which is occasionally an issue for MacOS users (even on OS X for misconfigured editors).

    • It often only surfaces as an issue when single-line // or # comments are used. Multiline /*...*/ comments do seldom disturb the parser when linebreaks get ignored.

  • If your syntax error does not transmit over the web: It happens that you have a syntax error on your machine. But posting the very same file online does not exhibit it anymore. Which can only mean one of two things:

    • You are looking at the wrong file!

    • Or your code contained invisible stray Unicode (see above). You can easily find out: Just copy your code back from the web form into your text editor.

  • Check your PHP version. Not all syntax constructs are available on every server.

    • php -v for the command line interpreter

    • <?php phpinfo(); for the one invoked through the webserver.


    Those aren't necessarily the same. In particular when working with frameworks, you will them to match up.

  • Don't use PHP's reserved keywords as identifiers for functions/methods, classes or constants.

  • Trial-and-error is your last resort.

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:

<?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.

回答2:

我认为这个话题太过讨论/太复杂了。使用IDE是完全避免任何语法错误的方法。我什至会说没有IDE的工作是不专业的。为什么?因为现代IDE在键入的每个字符之后都会检查语法。当您编写代码并且整行变成红色,并且大的警告提示告诉您语法错误的确切类型和确切位置时,那么就完全不需要搜索其他解决方案了。

使用语法检查IDE意味着:

您不会(有效地)再也不会遇到语法错误,仅仅是因为您在键入时就可以正确看到它们。认真。

具有语法检查功能的优秀IDE(所有Linux,Windows和Mac均可用):

  1. NetBeans [免费]
  2. PHPStorm [$ 199 USD]
  3. Eclipse PHP插件 [免费]
  4. Sublime [$ 80 USD](主要是文本编辑器,但可以通过插件进行扩展,例如 PHP语法解析器)

A2:

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):

  1. NetBeans [free]
  2. PHPStorm [$199 USD]
  3. Eclipse with PHP Plugin [free]
  4. Sublime [$80 USD] (mainly a text editor, but expandable with plugins, like PHP Syntax Parser)

回答3:

意外[

这些天来,意外的[数组括号在过时的PHP版本上很常见。由于PHP > = 5.4 <,短数组语法可用。 / strong>。较旧的安装仅支持array()

$php53 = array(1, 2, 3);
$php54 = [1, 2, 3];
         ⇑

数组函数结果解引用同样不适用于旧版本的PHP:

$result = get_whatever()["key"];
                      ⇑

参考-此错误在PHP中意味着什么? -"语法错误,意外的\[" 显示了最常见,最实用的解决方法。

但是,升级PHP安装始终会带来更好的效果。对于共享的虚拟主机计划,请先进行以下研究: SetHandlerphp56-fcgi可用于启用较新的运行时。

另请参阅:

顺便说一句,还有预处理器和 PHP 5.4语法下变频器如果您确实对较旧的+较慢的PHP版本感到固执。

意外的[ 语法错误的其他原因

如果不是PHP版本不匹配,则通常是普通的错字或新手语法错误:

  • 您不能使用类中的数组属性声明/表达式,甚至在PHP 7中也是如此。

    protected $var["x"] = "Nope";
                  ⇑
    
  • [与花括号大括号{或括号()混淆是常见的疏忽。

    foreach [$a as $b)
            ⇑
    
  • 或尝试将常量(在PHP 5.6之前)作为数组取消引用:

    $var = const[123];
           ⇑
    

    至少PHP将const解释为常量名称。

    如果要访问数组变量(这是此处的典型原因),请添加前导$标记-使其成为$varname。

  • 您正在尝试在关联数组的成员上使用global关键字。这是无效的语法:

    global $var['key'];
    


意外的] 关闭方括号

这种情况比较少见,但是在终止数组]括号中也会发生语法错误。

  • 再次与)括号或}花括号不匹配的情况很常见:

    function foobar($a, $b, $c] {
                              ⇑
    
  • 或者尝试在没有数组的地方结束数组:

    $var = 2];
    

    多行 嵌套数组声明。

    $array = [1,[2,3],4,[5,6[7,[8],[9,10]],11],12]],15];
                                                 ⇑
    

    如果是这样,请使用IDE进行括号匹配,以查找任何过早的]数组闭包。至少要使用更多的间距和换行符来缩小范围。

A3:

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 support array().

$php53 = array(1, 2, 3);
$php54 = [1, 2, 3];
         ⇑

Array function result dereferencing is likewise not available for older PHP versions:

$result = get_whatever()["key"];
                      ⇑

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 errors

If 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 PHP7.

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


Unexpected ] closing square 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-line and nested array 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.

回答4:

意外的T_VARIABLE

"意外的T_VARIABLE"表示存在一个字面的$variable名称,该名称不适合当前的表达式/语句结构。

  1. 缺少分号

    最通常表示缺少分号在上一行中。语句后的变量赋值可以很好地指示位置:

           ⇓
    func1()
    $var = 1 + 2;     # parse error in line +2
    
  2. 字符串连接

    经常发生的事故是字符串连接和被忘记的.运算符:

                                   ⇓
    print "Here comes the value: "  $value;
    

    顺便说一句,您最好使用字符串插值(双引号中的基本变量)。避免了这些语法问题。

    字符串插值是脚本语言的核心功能。利用它不会感到羞耻。忽略有关变量的任何微优化建议.串联的速度更快。 不是。

  3. 缺少表达式运算符

    当然,在其他表达式中也会出现相同的问题,例如算术运算:

               ⇓
    print 4 + 7 $var;
    

    PHP不能猜测,如果应该添加,减去或比较变量等。

  4. 列表

    与语法列表相同,例如在数组填充中,解析器还指示期望的逗号,例如:

                                          ⇓
    $var = array("1" => $val, $val2, $val3 $val4);
    

    或函数参数列表:

                                    ⇓
    function myfunc($param1, $param2 $param3, $param4)
    

    等效地,您是否使用listglobal语句看到此信息,或者在for循环中缺少;分号时。

  5. 类声明

    也会发生此解析器错误 。您只能分配静态常量,不能分配表达式。因此,解析器抱怨变量是分配的数据:

    class xyz {      ⇓
        var $value = $_GET["input"];
    

    不匹配的}大括号在这里尤其容易出现。如果方法过早终止(使用适当的缩进!),则通常会将杂散变量放到类声明主体中。

  6. 标识符后的变量

    您也永远不能拥有变量直接跟随标识符

                 ⇓
    $this->myFunc$VAR();
    

    顺便说一句,这是一个常见的示例,其意图是使用变量变量。在这种情况下,例如,使用$this->{"myFunc$VAR"}();进行变量属性查找。

    请记住,使用变量变量应该是例外。新手经常尝试太随意地使用它们,即使数组更简单,更合适。

  7. 在语言构造后缺少括号

    过分的打字可能会导致忘记ifforforeach 语句:

           ⇓
    foreach $array as $key) {
    

    解决方案:在语句和变量之间添加缺少的开头(

  8. Else不需要条件

         ⇓
    else ($var >= 0)
    

    解决方案:从else中删除条件或使用 elseif

  9. 需要用括号括起来

         ⇓
    function() uses $var {}
    

    解决方案:在$var周围加上括号。

  10. 不可见空格

    参考答案中所述,"不可见的杂散Unicode "(例如不间断空格),您可能还会看到此错误毫无疑问的代码,例如:

    <?php
                              ⇐
    $var = new PDO(...);
    

    在文件开头和复制粘贴代码中相当普遍。如果您的代码在外观上似乎不包含语法问题,请与hexeditor一起检查。

另请参见

A4:

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.

  1. 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:

           ⇓
    func1()
    $var = 1 + 2;     # parse error in line +2
    
  2. String concatenation

    A frequent mishap are string concatenations with 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 language core feature. No shame in utilizing it. Ignore any micro-optimization advise about variable . concatenation being faster. It's not.

  3. Missing expression operators

    Of course the same issue can arise in other expressions, for instance arithmetic operations:

               ⇓
    print 4 + 7 $var;
    

    PHP can't guess here if the variable should have been added, subtracted or compared etc.

  4. 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 or global statements, or when lacking a ; semicolon in a for loop.

  5. 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.

  6. Variables after identifiers

    You can also never have a variable follow an identifier directly:

                 ⇓
    $this->myFunc$VAR();
    

    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.

    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.

  7. Missing parentheses after language constructs

    Hasty typing may lead to forgotten opening parenthesis for if and for and foreach statements:

           ⇓
    foreach $array as $key) {
    

    Solution: add the missing opening ( between statement and variable.

  8. Else does not expect conditions

         ⇓
    else ($var >= 0)
    

    Solution: Remove the conditions from else or use elseif.

  9. Need brackets for closure

         ⇓
    function() uses $var {}
    

    Solution: Add brackets around $var.

  10. 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:

    <?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.

See also

回答5:

意外的T_CONSTANT_ENCAPSED_STRING
意外的T_ENCAPSED_AND_WHITESPACE

笨拙的名称T_CONSTANT_ENCAPSED_STRINGT_ENCAPSED_AND_WHITESPACE指的是引用的 "字符串" 文字

它们在不同的上下文中使用,但是语法问题非常相似。在双引号字符串上下文中会出现 T_ENCAPSED…警告,而在简单的PHP表达式或语句中, T_CONSTANT…字符串通常会误入歧途。

  1. 不正确的变量插值

    并且最经常出现错误的PHP变量插值:

                              ⇓     ⇓
    echo "Here comes a $wrong['array'] access";
    

    在PHP中必须引用数组键上下文。但是在双引号字符串(或HEREDOC)中,这是一个错误。解析器抱怨包含单引号的'string',因为它通常在那里期望一个文字标识符/键。

    更确切地说,使用PHP2样式的双引号内的简单语法用于数组引用:

    < pre>

    嵌套数组或更深的对象引用,但是需要复杂的卷曲字符串表达式语法:

    echo "This is only $valid[here] ...";
    

    如果不确定,通常使用起来更安全。它甚至经常被认为更具可读性。更好的IDE实际上为此使用了不同的语法着色。

  2. 缺少串联

    如果字符串在表达式之后,但是缺少串联或其他运算符,则您会看到PHP抱怨字符串文字:

    echo "Use {$array['as_usual']} with curly syntax.";
    
  3. 令人困惑的字符串引号括起来

    混淆字符串定界符。以单个'或双"引号开头的字符串也以相同的结尾。

                           ⇓
    print "Hello " . WORLD  " !";
    

    该示例以double开头引号。但是双引号也被指定为HTML属性。然而,其中的预期串联运算符却被解释为单引号中第二个字符串的一部分。

    提示:将编辑器/ IDE设置为对单引号和双引号字符串使用略微不同的颜色。 (这也有助于应用程序逻辑更喜欢例如,双引号字符串用于文本输出,而单引号字符串仅用于类似常量的值。)

    这是一个很好的示例,在这里您不应该首先用双引号引起来。相反,只需使用正确的\" 转义表示HTML属性的引号:

                    ⇓
    print "<a href="' . $link . '">click here</a>";
          ⌞⎽⎽⎽⎽⎽⎽⎽⎽⌟⌞⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⌟⌞⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⌟
    

    虽然这也会导致语法混乱,但是所有更好的IDE /编辑器都通过将转义的引号着色来再次提供帮助不一样。

  4. 缺少引号

    等效地是忘记打开" / '引号解析器错误的秘诀:

    print "<a href=\"{$link}\">click here</a>";
    

    在这里,','会变成裸字后面的字符串文字,而显然login应该是字符串参数。

  5. 数组列表

    如果错过了数组创建块中的,逗号,则解析器将看到两个连续的字符串:

                   ⇓
     make_url(login', 'open');
    
  6. 函数参数列表

    同一件事用于函数调用

    array(               ⇓
         "key" => "value"
         "next" => "....",
    );
    
  7. 失控的字符串

    一个常见的变种是完全被遗忘的字符串终止符:

                             ⇓
    myfunc(123, "text", "and"  "more")
    

    此处PHP抱怨两个字符串文字彼此紧随其后。但真正的原因当然是先前未公开的字符串。

另请参见

A5:

Unexpected T_CONSTANT_ENCAPSED_STRING
Unexpected T_ENCAPSED_AND_WHITESPACE

The unwieldy names T_CONSTANT_ENCAPSED_STRING and T_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.

  1. 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 quotes for array references:

    echo "This is only $valid[here] ...";
    

    Nested arrays or deeper object references however require the complex curly string expression syntax:

    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.

  2. 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 guess that the string was meant to be appended there.

  3. 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 \" escapes for 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.

  4. Missing opening quote

    Equivalently are forgotten opening "/' quotes a recipe for parser errors:

                   ⇓
     make_url(login', 'open');
    

    Here the ', ' would become a string literal after a bareword, when obviously login was meant to be a string parameter.

  5. 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.

  6. Function parameter lists

    The same thing for function calls:

                             ⇓
    myfunc(123, "text", "and"  "more")
    
  7. 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.

See also

回答6:

意外的T_STRING

T_STRING有点用词不当。它不引用带引号的"字符串"。这意味着遇到了原始标识符。范围可以从bare单词到剩余的CONSTANT或函数名称,忘记的未加引号的字符串或任何纯文本。

  1. 引用不正确的字符串

    但是,对于错误引用的字符串值,此语法错误最常见。任何未转义且散乱的"'引号将形成无效的表达式:

                   ⇓                  ⇓
     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变量值,而是专注于忘记源代码的代码段。示例是此处

    另请参见 什么 中的单引号和双引号字符串之间的区别是什么? 。

  2. 未封闭的字符串

    如果您缺少结尾的" ,然后通常会出现语法错误。未终止的字符串通常会消耗一些代码,直到下一个预期的字符串值为止:

                                                           ⇓
    echo "Some text", $a_variable, "and some runaway string ;
    success("finished");
             ⇯
    

    解析器随后可能会抗议的不只是文字T_STRING,另一个常见的变化是 意外的'>' 用于未引用的文字HTML。

  3. 未编程的字符串引号

    如果您从博客或网站复制并粘贴代码,则有时会得到无效的代码。 印刷报价不是 PHP期望的:

    $text = ’Something something..’ + ”these ain't quotes”;
    

    印刷/智能引号是Unicode符号。 PHP将它们视为相邻的字母数字文本的一部分。例如,"these被解释为常量标识符。但是随后的任何文本文字都会被解析器视为裸字/ T_STRING。

  4. 缺少的分号;再次

    如果您在前几行中有一个未终止的表达式,那么任何以下语句或语言构造都将被视为原始标识符:

           ⇓
    func1()
    function2();
    

    PHP不能知道您是要一个接一个地运行两个函数,还是要乘以它们的结果,相加或比较它们,还是只运行一个||或另一个。

  5. PHP脚本中的短打开标记和 标头

    这很不常见。但是,如果启用了short_open_tags,则您将无法开始PHP脚本

          ⇓
    <?xml version="1.0"?>
    

    PHP将看到 并自行回收。它无法理解流浪xml的含义。它将被解释为常量。但是version将被视为另一个文字/常量。而且由于解析器无法在两个后续的文字/值之间没有表达式运算符的意义,因此将导致解析器失败。

  6. 不可见的Unicode字符

    导致语法错误的最可怕原因是Unicode符号,例如不间断空格。 PHP允许将Unicode字符用作标识符名称。如果您收到T_STRING解析器投诉,该投诉涉及完全不可信的代码,例如:

    <?php
        print 123;
    

    ,则需要拆开另一个文本编辑器。或什至是一个六角编辑器。此处看起来像普通空格和换行符的内容可能包含不可见的常量。基于Java的IDE有时会忽略UTF-8 BOM表,零宽度空格,段落分隔符等问题。尝试重新编辑所有内容,删除空白并重新添加普通空格。

    您可以缩小通过在每行开头添加多余的;语句分隔符来减少它:

    <?php
        ;print 123;
    

    多余的;分号将转换前一个不可见字符到一个未定义的常量引用中(以语句形式表示)。作为回报,PHP会发出有用的通知。

  7. 变量名前面缺少`$`符号

    PHP变量由美元符号表示,后跟变量名称。

    美元符号($)是<用于将标识符标记为变量名称的href=" https: en.wikipedia.org wiki sigil_(computer_programming)" rel="nofollow noreferrer"> sigil 。如果没有此标记,则标识符可以是 语言关键字常量

    当PHP代码为用其他语言(C,Java,JavaScript等)编写的代码进行"翻译"。在这种情况下,变量类型的声明(当原始代码使用使用类型变量的语言编写时)也会潜行并产生此错误。

  8. 转义引号

    如果在字符串中使用\,则具有特殊含义。这称为" 转义字符",通常告诉解析器从字面上取下一个字符。

    例如:echo'Jimsaid\'Hello\';将打印Jim说'hello'

    如果不对字符串的右引号进行转义,则将按字面意义而不是按预期方式使用右引号,即作为可打印的引号作为字符串的一部分而不关闭字符串。在打开下一个字符串或在脚本末尾,这通常显示为解析错误。

    在Windows中指定路径时,非常常见的错误:"C:\xampp\htdocs\"是错误的。您需要"C:\\xampp\\htdocs\\"

A6:

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 from bare words to leftover CONSTANT or function names, forgotten unquoted strings, or any plain text.

  1. 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 HEREDOC section.

    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 here

    See also What is the difference between single-quoted and double-quoted strings in PHP?.

  2. 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_STRINGs which the parser may protest then. Another frequent variation is an Unexpected '>' for unquoted literal HTML.

  3. 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:

    $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.

  4. 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.

  5. Short open tags and <?xml headers in PHP scripts

    This 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 stray xml was meant for. It'll get interpreted as constant. But the version 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.

  6. 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.

  7. 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.

  8. 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'

    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\\".

回答7:

意外(

括号通常遵循以下语言结构,例如if / foreach / for / array / 列出或开始一个算术表达式。在语法上,在"字符串",上一个(),一个单独的$之后,以及某些典型的声明上下文中,它们在语法上是不正确的。

  1. 函数声明参数

    此错误的罕见情况是尝试将表达式用作默认函数参数。即使在PHP7中也不支持此功能:

    function header_fallback($value, $expires = time() + 90000) {
    

    函数声明中的参数只能是文字值或常量表达式。与函数调用不同,可以自由使用whatever(1+something()*2)等。

  2. 类属性默认值

    类成员声明中,其中只允许使用文字/常量值,而不是表达式:

    class xyz {                   ⇓
        var $default = get_config("xyz_default");
    

    将此类内容放入构造函数中。另请参见为什么PHP属性不允许使用函数?

    < p>再次注意,PHP 7仅允许var$xy=1+2+3;常量表达式。

  3. PHP中的JavaScript语法

    使用JavaScript或 jQuery语法出于明显的原因在PHP中不起作用:

    <?php      ⇓
        print $(document).text();
    

    发生这种情况时,通常表示未终止的前面的字符串;和文字

A7:

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.

  1. 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.

  2. 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.

  3. JavaScript syntax in PHP

    Using JavaScript or jQuery syntax won't work in PHP for obvious reasons:

    <?php      ⇓
        print $(document).text();
    

    When this happens, it usually indicates an unterminated preceding string; and literal <script> sections leaking into PHP code context.

  4. isset(()), empty, key, next, current

    Both isset() and empty() are language built-ins, not functions. They need to access a variable directly. If you inadvertently add a pair of parentheses too much, then you'd create an expression however:

              ⇓
    if (isset(($_GET["id"]))) {
    

    The same applies to any language construct that requires implicit variable name access. These built-ins are part of the language grammar, therefore don't permit decorative extra parentheses.

    User-level functions that require a variable reference -but get an expression result passed- lead to runtime errors instead.


Unexpected )

  1. Absent function parameter

    You cannot have stray commas last in a function call. PHP expects a value there and thusly complains about an early closing ) parenthesis.

                  ⇓
    callfunc(1, 2, );
    

    A trailing comma is only allowed in array() or list() constructs.

  2. 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.

  3. Foreach as constant

    For forgotten variable $ prefixes in control statements you will see:

                       ↓    ⇓
    foreach ($array as wrong) {
    

    PHP here sometimes tells you it expected a :: instead. Because a class::$variable could have satisfied the expected $variable expression..


Unexpected {

Curly braces { and } enclose code blocks. And syntax errors about them usually indicate some incorrect nesting.

  1. 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.

  2. { 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}.

  3. 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.


Unexpected }

When getting an "unexpected }" error, you've mostly closed a code block too early.

  1. 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.

  2. 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.


Unexpected {, expecting (

Language constructs which require a condition/declaration header and a code block will trigger this error.

  1. Parameter lists

    For example misdeclared functions without parameter list are not permitted:

                     ⇓
    function whatever {
    }
    
  2. 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.

回答8:

意外的$ end

当PHP谈论"意外的$end"时,表示您的代码过早结束。 (从字面上看,该消息有点误导。这与新人有时假定的名为" $ end"的变量无关。它指的是"文件结尾", EOF 。)

原因:代码块/和函数或类声明的{}不平衡。

几乎总是关于缺少}大括号以关闭前面的代码块的情况。

  • 再次,使用适当的缩进以避免此类问题。

  • 使用带有括号匹配的IDE找出}的位置。大多数IDE和文本编辑器中都有键盘快捷键:

    • NetBeans,PhpStorm,Komodo: Ctrl [ Ctrl ]
    • Eclipse,Aptana: Ctrl Shift P
    • Atom,Sublime: Ctrl m -Zend Studio Ctrl M
    • Geany,记事本++: Ctrl B -乔: Ctrl G -Emacs: CMn < / kbd>-Vim:

大多数IDE也会突出显示匹配的花括号,括号和括号。这使得检查它们的相关性非常容易:

不终止表达式

意外的$end语法/解析器错误也可能发生于未终止的表达式或语句:

  • $var=func(1, ?> EOF

因此,首先查看脚本的结尾。对于任何PHP脚本中的最后一条语句,结尾的;通常是多余的。但是您应该有一个。正是因为它缩小了此类语法问题的范围。

缩进的HEREDOC标记

另一个常见的情况出现在 HEREDOC或NOWDOC 字符串。终止标记会被前导空格,制表符等忽略:

print <<< END
    Content...
    Content....
  END;
# ↑ terminator isn't exactly at the line start

因此,解析器假定HEREDOC字符串继续到文件末尾(因此为"意外$ end")。几乎所有的IDE和语法高亮的编辑器都会对此加以说明或发出警告。

转义引号

如果在字符串中使用\,则具有特殊含义。这称为" 转义字符",通常告诉解析器从字面上取下一个字符。

示例:echo'Jimsaid\'Hello\';将打印Jim说'hello'

如果您对字符串的右引号进行转义,则将按字面意义而不是按预期方式使用右引号,即作为可打印引号作为字符串的一部分而不关闭字符串。通常,在打开下一个字符串或在脚本末尾,这将显示为解析错误。

在Windows中指定路径时,非常常见的错误:"C:\xampp\htdocs\"是错误的。您需要"C:\\xampp\\htdocs\\"

替代语法

在模板中的语句/代码块使用替代语法时,您会看到此语法错误的情况很少见。例如,使用if:else:和缺少的endif;

另请参见:

A8:

Unexpected $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.)

Cause: Unbalanced { and } for code blocks / and function or class declarations.

It's pretty much always about 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: %

Most IDEs also highlight matching braces, brackets and parentheses. Which makes it pretty easy to inspect their correlation:

Unterminated expressions

And Unexpected $end syntax/parser error can also occur for unterminated expressions or statements:

  • $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 should have one. Precisely because it narrows such syntax issues down.

Indented HEREDOC markers

Another common occurrence appears with HEREDOC or NOWDOC strings. The terminating marker goes ignored with leading spaces, tabs, etc.:

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.

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'

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\\".

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.

See also:

回答9:

意外的T_IF
意外的T_ELSEIF
意外的T_ELSE
意外的T_ENDIF

条件控制块ifelseifelse遵循简单的结构。当您遇到语法错误时,很可能只是无效的块嵌套→缺少{大括号}或太多。

  1. 由于缩进不正确而缺少{}

    格式不正确的代码括号常见于格式较差的代码,例如:< / p>

    if((!($opt["uniQartz5.8"]!=$this->check58)) or (empty($_POST['poree']))) {if
    ($true) {echo"halp";} elseif((!$z)or%b){excSmthng(False,5.8)}elseif (False){
    

    如果您的代码如下所示,请重新开始!否则,您或其他任何人都无法修复。在Internet上展示此内容以寻求帮助是没有意义的。

    如果您可以直观地遵循if / else条件条件及其的嵌套结构和关系,则只能修复它.{代码块}。使用您的IDE来查看它们是否都配对。

    if (true) {
         if (false) {
                  …
         }
         elseif ($whatever) {
             if ($something2) {
                 …
             } 
             else {
                 …
             }
         }
         else {
             …
         }
         if (false) {    //   a second `if` tree
             …
         }
         else {
             …
         }
    }
    elseif (false) {
        …
    }
    

    任何双} }都不会仅关闭分支,但是是先前的条件结构。因此坚持一种编码风格;不要在嵌套的if / else树中混合和匹配。

    除了这里的一致性以外,事实证明,避免冗长的条件也很有用。使用临时变量或函数来避免if-表达式。

  2. IF不能在表达式中使用

    一个令人惊讶的常见新人错误是试图在表达式中使用if语句,例如作为打印语句:

                       ⇓
    echo "<a href='" . if ($link == "example.org") { echo …
    

    这当然是无效的。

    您可以使用三元条件,但要注意可读性

    echo "<a href='" . ($link ? "http://yes" : "http://no") . "</a>";
    

    否则,请破坏此类输出构造:使用如果secho s 是多个。
    更好的是,使用临时变量,然后将条件放在以下位置:

    if ($link) { $href = "yes"; } else { $href = "no"; }
    echo "<a href='$href'>Link</a>";
    

    定义函数或此类情况下的方法通常也很有意义。

    控制块不返回"结果"

    现在这种情况不那么常见了,但是一些编码人员甚至尝试处理好像可以返回结果

    $var = if ($x == $y) { "true" };
    

    在结构上与在字符串中使用if相同串联/表达式。

    • 但是控制结构(如果/ foreach / while)没有"结果"
    • 文字字符串" true"也只是一个空语句。

    您将不得不在代码块中使用赋值

    if ($x == $y) { $var = "true"; }
    

    或者,使用吗?:三元比较。

    If in

    无法在条件中嵌套if

                        ⇓
    if ($x == true and (if $y != false)) { ... }
    

    显然这是多余的,因为(或or)已经允许链接比较。

  3. 被遗忘的;分号

    一次:每个控制块都需要一个语句。如果上一个代码段没有以分号结尾,则可以保证语法错误:

                    ⇓
    $var = 1 + 2 + 3
    if (true) { … }
    

    Btw,{…}代码块也需要分号。

  4. 分号为时过早

    现在责怪特定的编码样式可能是错误的,因为这种陷阱很容易忽略:

                ⇓
    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分支。

  5. 不使用代码块

    在语法上,对于if <中的代码块,可以省略花括号> { ... } / code> / elseif / else分支。令人遗憾的是,这是不熟练的编码人员非常常用的语法样式。 (在错误的假设下,这样可以更快地键入或阅读)。

    但是,这很有可能会使语法失效。早晚会有其他语句进入if / else分支:

    if (true)
        $x = 5;
    elseif (false)
        $x = 6;
        $y = 7;     ←
    else
        $z = 0;
    

    但是要实际使用代码块,您 必须 像这样写{ ... }

    即使经验丰富的程序员也避免使用这种无括号的语法,或者至少将其理解为该规则的例外。

  6. 其他/ Elseif顺序错误

    提醒自己的一件事是条件订单,当然。

    if ($a) { … }
    else { … }
    elseif ($b) { … }
    ↑
    

    您可以根据需要设置任意数量的elseif,但 else必须倒数。就是这样。

  7. 类声明

    如上所述 ,您不能拥有控制语句在类声明中:

    class xyz {
        if (true) {
            function ($var) {}
        }
    

    您要么忘记了一个函数定义,或者在这种情况下过早关闭了一个}

  8. 意外的T_ELSEIF / T_ELSE

    混合使用PHP和HTML时,if/elseif的结束}必须位于同一位置PHP块 作为下一个elseif/else。如果需要将elseif的一部分包含在elseif中,则将生成错误,因为的结束}

    <?php if ($x) { ?>
        html
    <?php } ?>
    <?php elseif ($y) { ?>
        html
    <?php } ?>
    

    正确的格式

    <?php if ($x) { ?>
        html
    <?php } elseif ($y) { ?>
        html
    <?php } ?>
    

    这或多或少是错误缩进的一种变体-大概经常基于错误的编码意图。
    您不能 ifelseif / else结构标记之间混搭其他语句:

    < pre>

    任何一种都只能出现在{…}代码块中,而不能出现在控制结构标记之间。

    • 这根本没有道理。当PHP在ifelse分支之间跳转时,并不是像有些"未定义"状态。
    • 您必须确定打印语句属于/的位置,或者是否需要在两个分支中都重复打印语句。

    您也不能在不同的控制结构之间 if / else

    if (true) {
    }
    echo "in between";    ←
    elseif (false) {
    }
    ?> text <?php      ←
    else {
    }
    

    没有语法关系foreach的词法作用域以}结尾,因此if结构继续下去是没有意义的。

  9. T_ENDIF

    如果抱怨意外的T_ENDIF,则使用其他语法样式if:elseif:else:endif;。您应该三思而后行。

    • 一个常见的陷阱是使类似的:冒号,用于;分号。 (在"分号中为时过早")

    • 由于缩进在模板文件中更难跟踪,因此使用替代语法时缩进更多-可能您的endif;与任何if:不匹配。

    • 使用 }endif; double if终止符。

    "意外的$ end"通常是被遗忘的}大括号的价格。

  10. 分配与比较

    因此,这不是语法错误,但是在这种情况下值得一提:

    foreach ($array as $i) {
        if ($i) { … }
    }
    else { … }
    

    == / ===比较,但是=分配。这相当微妙,并且很容易导致某些用户无助地编辑整个条件块。首先要当心意外的任务-每当您遇到逻辑故障/行为异常时。

A9:

Unexpected T_IF
Unexpected T_ELSEIF
Unexpected T_ELSE
Unexpected 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.

  1. Missing { or } due to incorrect indentation

    Mismatched 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.

  2. IF cannot be used in expressions

    A 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 ifs and echos.
    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 (or or) already allows chaining comparisons.

  3. Forgotten ; semicolons

    Once 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.

  4. 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 the if, and would always run.
    • So the else no longer had a relation to an open if 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 whole if construct, severing the else branch syntactically.

  5. Not using code blocks

    It's syntactically allowed to omit curly braces {} for code blocks in if/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 have to write {} them as such!

    Even seasoned programmers avoid this braceless syntax, or at least understand it as an exceptional exception to the rule.

  6. 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 elseifs as you want, but else has to go last. That's just how it is.

  7. 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 function definition, or closed one } too early in such cases.

  8. Unexpected T_ELSEIF / T_ELSE

    When mixing PHP and HTML, the closing } for an if/elseif must be in the same PHP block <?php ?> as the next elseif/else. This will generate an error as the closing } for the if needs to be part of the elseif:

    <?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 inbetween if and elseif/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 and else 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/else between different control structures:

    foreach ($array as $i) {
        if ($i) { … }
    }
    else { … }
    

    There is no syntactic relation between the if and else. The foreach lexical scope ends at }, so there's no point for the if structure to continue.

  9. 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 any if:.

    • Using } endif; is a doubled if-terminator.

    While an "unexpected $end" is usually the price for a forgotten closing } curly brace.

  10. 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.

回答10:

意外的T_IF
意外的T_FOREACH
意外的T_FOR
意外的T_WHILE
意外的T_DO
意外的T_ECHO

控制结构,例如ifforeachforwhilelistglobalreturndoprintecho作为陈述。他们通常自己一个人居住。

  1. 分号;你在哪?

    在上一行中,您普遍缺少分号如果解析器抱怨控制语句:

                 ⇓
    $x = myfunc()
    if (true) {
    

    解决方案:查看上一行;添加分号。

  2. 类声明

    发生这种情况的另一个位置是在类声明中。在类部分中,您只能列出属性初始化和方法部分。

    class xyz {
        if (true) {}
        foreach ($var) {}
    

    这种语法错误通常是由于错误嵌套的{}导致的。特别是当功能代码块关闭得太早时。

  3. 表达式上下文中的语句

    大多数语言构造都可以仅用作语句。它们不是要放在其他表达式中:

                       ⇓
    $var = array(1, 2, foreach($else as $_), 5, 6);
    

    同样,您不能在字符串,数学表达式或其他地方使用if吗? / p>

                   ⇓
    print "Oh, " . if (true) { "you!" } . " won't work";
    // Use a ternary condition here instead, when versed enough.
    

    要专门在表达式中嵌入类似if的条件,通常需要使用 ?:三元评估

    < ,whileglobalecho和较小的扩展list。 >

              ⇓
    echo 123, echo 567, "huh?";
    

    print()是一种内置语言,可以在表达式上下文中使用。 (但很少有道理。)

  4. 保留关键字作为标识符

    对于用户定义的函数,您也不能使用doif和其他语言构造类名。 (也许在PHP 7中。但是即使那样,还是不可取的。)

A10:

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.

  1. Semicolon; where you at?

    Pretty universally have you missed a semicolon in the previous line if the parser complains about a control statement:

                 ⇓
    $x = myfunc()
    if (true) {
    

    Solution: look into the previous line; add semicolon.

  2. 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.

    class xyz {
        if (true) {}
        foreach ($var) {}
    

    Such syntax errors commonly materialize for incorrectly nested { and }. In particular when function code blocks got closed too early.

  3. Statements in expression context

    Most language constructs can only be used as statements. They aren't meant to be placed inside other expressions:

                       ⇓
    $var = array(1, 2, foreach($else as $_), 5, 6);
    

    Likewise can't you use an if in strings, math expressions or elsewhere:

                   ⇓
    print "Oh, " . if (true) { "you!" } . " won't work";
    // Use a ternary condition here instead, when versed enough.
    

    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 extend list.

              ⇓
    echo 123, echo 567, "huh?";
    

    Whereas print() is a language built-in that may be used in expression context. (But rarely makes sense.)

  4. Reserved keywords as identifiers

    You also can't use do or if and other language constructs for user-defined functions or class names. (Perhaps in PHP7. But even then it wouldn't be advisable.)

回答11:

意外的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表达式。如果解析器抱怨它们,那么通常意味着它们周围的 ( )解析不正确或不匹配。

  1. Parens分组

    特别是对于具有多个比较的if语句,您必须注意正确计数打开和关闭括号

                            ⇓
    if (($foo < 7) && $bar) > 5 || $baz < 9) { ... }
                          ↑
    

    如果<if构造,从而使这里的code>条件已经被)

    终止

  2. isset()与比较混在一起

    一个常见的新手是pitfal试图结合 isset() empty() 进行比较:

                            ⇓
    if (empty($_POST["var"] == 1)) {
    

    甚至:

                        ⇓
    if (isset($variable !== "value")) {
    

    这对PHP没有意义,因为isset empty是仅接受变量名称的语言构造。比较结果也没有意义,因为输出仅/已经是布尔值。

  3. =>数组运算符混淆> = 更大或更等于

    两个运算符看起来都有些相似,因此有时会得到混淆:

             ⇓
    if ($var => 5) { ... }
    

    您只需要记住该比较运算符被称为" 大于等于"即可

    另请参见: PHP中的if语句结构

  4. 没什么可比的

    如果两个比较具有相同的变量名称,则也无法将它们组合在一起:

                     ⇓
    if ($xyz > 5 and < 100)
    

    PHP可以" t推断您打算再次比较初始变量。表达式通常根据运算符优先级进行配对,因此看到<,原始变量只剩下一个布尔结果。

    另请参见:意外的T_IS_SMALLER_OR_EQUAL

  5. 比较链

    您不能与带有一排运算符的变量进行比较:

                      ⇓
     $reult = (5 < $x < 10);
    

    必须将其分解为两次比较,每一次都是针对$x

    实际上,这是黑名单表达式的一种情况(由于等效的运算符关联性)。在某些C风格的语言中,它在语法上是有效的,但是PHP也不会将其解释为预期的比较链。

  6. 意外>
    意外<

    大于> 或小于 <运算符没有自定义的T_XXX标记程序名称。而且,尽管它们可能像其他所有对象一样放错了位置,但您更经常会看到解析器抱怨它们使用了错误引用的字符串和混搭的HTML:

                            ⇓
    print "<a href='z">Hello</a>";
                     ↑
    

    这等于字符串"

A11:

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 as if expressions. If the parser complains about them, then it often means incorrect paring or mismatched ( ) parens around them.

  1. 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.

  2. isset() mashed with comparing

    A common newcomer is pitfal is trying to combine isset() or empty() with comparisons:

                            ⇓
    if (empty($_POST["var"] == 1)) {
    

    Or even:

                        ⇓
    if (isset($variable !== "value")) {
    

    This doesn't make sense to PHP, because isset and empty 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.

  3. Confusing >= greater-or-equal with => array operator

    Both 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 than or equal" to get it right.

    See also: If statement structure in PHP

  4. 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

  5. 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.

  6. Unexpected >
    Unexpected <

    The greater than > or less than < operators don't have a custom T_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 constant Hello 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(); ?>
               ↑
    

See also:

回答12:

意外的'?'

如果您尝试在PHP 7之前的版本中使用空合并运算符??,则会出现此错误。

<?= $a ?? 2; // works in PHP 7+
<?= (!empty($a)) ? $a : 2; // All versions of PHP

意外的'?',期望变量

可为空的类型可能会发生类似的错误,如下所示:

function add(?int $sum): ?int {

这再次表明使用了过时的PHP版本(CLI版本php-v或网络服务器绑定了一个phpinfo();)。

A12:

Unexpected '?'

If you are trying to use the null coalescing operator ?? in a version of PHP prior to PHP 7 you will get this error.

<?= $a ?? 2; // works in PHP 7+
<?= (!empty($a)) ? $a : 2; // All versions of PHP

Unexpected '?', expecting variable

A similar error can occur for nullable types, as in:

function add(?int $sum): ?int {

Which again indicates an outdated PHP version being used (either the CLI version php -v or the webserver bound one phpinfo();).

回答13:

意外的T_LNUMBER

令牌T_LNUMBER表示"长" /数字。

  1. 无效的变量名

    在PHP和大多数其他编程语言中,变量不能以数字开头。第一个字符必须是字母或下划线。

    $1   // Bad
    $_1  // Good
    

    • 经常出现在PHP上下文中使用preg_replace -placeholders "$1"的地方:

      #                         ↓            ⇓  ↓
      preg_replace("/#(\w+)/e",  strtopupper($1) )
      

      应在回调处加引号的位置。 (现在已经不赞成使用/e regex标志。但是有时仍会在preg_replace_callback函数中误用它。)

    • 相同的标识符约束适用于对象属性,顺便说一句。

             ↓
      $json->0->value
      
    • 虽然令牌生成器/解析器不允许将文字$1作为变量名,但一个可以使用${1}${"1"}。这是非标准标识符的语法解决方法。 (最好将其视为本地范围查找。但是通常:在这种情况下,更喜欢使用纯数组!)

    • 有趣的是,但非常不推荐,PHP的解析器允许使用Unicode标识符。这样$➊才有效。 (与文字1不同)。

  2. 杂散数组条目

    数组声明-当缺少,逗号时:

    #            ↓ ↓
    $xy = array(1 2 3);
    

    或者类似的函数调用和声明以及其他构造:

    • func(1,23);
    • 函数xy($z2);
    • for($i=23<$z)

    因此通常不存在用于分隔列表或表达式的;之一。

  3. HTML引用错误

    再次,引号错误的字符串是流浪数字的常见来源:

    #                 ↓ ↓          
    echo "<td colspan="3">something bad</td>";
    

    这种情况应该或多或少地像意外的T_STRING 错误。

  4. 其他标识符

    函数,类或命名空间可以以数字开头:

             ↓
    function 123shop() {
    

    与变量名几乎相同。

A13:

Unexpected T_LNUMBER

The token T_LNUMBER refers to a "long" / number.

  1. 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.

    $1   // Bad
    $_1  // Good
    

    • Quite often comes up for using preg_replace-placeholders "$1" in PHP context:

      #                         ↓            ⇓  ↓
      preg_replace("/#(\w+)/e",  strtopupper($1) )
      

      Where the callback should have been quoted. (Now the /e regex flag has been deprecated. But it's sometimes still misused in preg_replace_callback functions.)

    • The same identifier constraint applies to object properties, btw.

             ↓
      $json->0->value
      
    • 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 literal 1).

  2. Stray array entry

    An unexpected long can also occur for array declarations - when missing , commas:

    #            ↓ ↓
    $xy = array(1 2 3);
    

    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.

  3. Misquoted HTML

    And again, misquoted strings are a frequent source of stray numbers:

    #                 ↓ ↓          
    echo "<td colspan="3">something bad</td>";
    

    Such cases should be treated more or less like Unexpected T_STRING errors.

  4. Other identifiers

    Neither functions, classes, nor namespaces can be named beginning with a number either:

             ↓
    function 123shop() {
    

    Pretty much the same as for variable names.

回答14:

意外的'='

这可能是由于变量名中包含无效字符引起的。变量名称​​必须遵循以下规则:

变量名称与PHP中的其他标签遵循相同的规则。有效的变量名称以字母或下划线开头,后跟任意数量的字母,数字或下划线。作为正则表达式,它将表示为:" [[a-zA-Z_ \ x7f- \ xff] [a-zA-Z0-9_ \ x7f- \ xff] *"

A14:

Unexpected '='

This can be caused by having invalid characters in a variable name. Variables names must follow these rules:

Variable names follow the same rules as other labels in PHP. A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'

回答15:

意外的"继续"(T_CONTINUE)

continue是一条语句(例如for或if),并且必须独立出现。它不能用作表达式的一部分。在某种程度上,因为continue不会返回值,但是在表达式中,每个子表达式都必须产生某个值,因此整体表达式会产生一个值。那就是语句和表达式之间的区别。

这意味着continue不能在三元语句或任何需要返回值的语句中使用。

意外的"中断"(T_BREAK)

当然,break;也一样。它也不能在表达式上下文中使用,而是一个严格的语句(与foreachif块处于同一级别)。

意外的"返回"(T_RETURN)

现在,对于return来说,这可能更令人惊讶,但这也只是块级的声明。它的确向更高的作用域/函数返回一个值(或NULL),但它不作为表达式本身求值。 →即:做return(return(false());;

A15:

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 as foreach or an if 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 doing return(return(false);;

回答16:

意外的" endwhile"(T_ENDWHILE)

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

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

此语法的替代方法是使用大括号:

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

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

A16:

Unexpected 'endwhile' (T_ENDWHILE)

The syntax is using a colon - if there is no colon the above error will occur.

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

The alternative to this syntax is using curly brackets:

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

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

回答17:

parse错误:语法错误,意外的':'开头的错误消息可能是由于将类静态引用Class::$Variable错误地编写为类别:$ Variable

A17:

An error message that begins Parse error: syntax error, unexpected ':' can be caused by mistakenly writing a class static reference Class::$Variable as Class:$Variable.

回到顶部