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

本文详细介绍了PHP编程中常见的语法错误类型,如T_STRING、T_VARIABLE、T_CONSTANT_ENCAPSED_STRING等,并提供了如何理解错误信息、检查代码上下文以及使用语法高亮工具来解决这些问题的方法。此外,还强调了错误行号的重要性,提醒开发者注意代码缩进、使用IDE或编辑器辅助以及查阅官方手册来提高解决问题的效率。
摘要由CSDN通过智能技术生成

本文翻译自: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 PHP解析错误:语法错误,第20行的index.php中出现意外的'{'

The unexpected symbol isn't always the real culprit. 意外的符号并不总是真正的罪魁祸首。 But the line number gives a rough idea of where to start looking. 但是行号给出了从哪里开始寻找的粗略想法。

Always look at the code context . 始终查看代码上下文 The syntax mistake often hides in the mentioned 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. 尽管Stack Overflow也欢迎新手程序员,但它主要针对专业编程问题。

  • Answering everyone's coding mistakes and narrow typos is considered mostly off-topic. 回答每个人的编码错误和狭窄的拼写错误通常被认为是题外话。
  • So please take the time to follow the basic steps , before posting syntax fixing requests. 因此,请花一些时间遵循基本步骤 ,然后再发布语法修复请求。
  • If you still have to, please show your own solving initiative, attempted fixes, and your thought process on what looks or might be wrong. 如果仍然需要,请展示您自己的解决方案,尝试的解决方案以及您对外观或错误之处的思考过程。

If your browser displays error messages such as "SyntaxError: illegal character", then it's not actually -related, but a - syntax error . 如果您的浏览器显示诸如“ SyntaxError:非法字符”之类的错误消息,则实际上与相关,而不是与相关的语法错误


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 vendor's requirements against your platform setup. 供应商代码上引发的语法错误:最后,请考虑如果语法错误不是由于编辑代码库而引起的,而是在外部供应商软件包安装或升级后出现的,则可能是由于PHP版本不兼容所致,因此请针对平台设置检查供应商的要求。


#1楼

参考:https://stackoom.com/question/1DjeB/PHP解析-语法错误-以及如何解决它们


#2楼

What are the syntax errors? 语法错误是什么?

PHP belongs to the C-style and imperative programming languages. PHP属于C风格命令式编程语言。 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 . IDE或编辑器用于PHP突出显示语法 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 ' ; 解析错误:语法错误,意外T_STRING ,期待' ; ' in file.php on line 217 ' 217 行的 file.php中

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. 诸如T_STRING名字解释了解析器/令牌最终不能处理的符号。 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 . Whitespace是您的朋友 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. 将复杂的if语句拆分为不同的条件或嵌套的if条件。

    • 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. if理解, if首选纯if语句。

    • PHP's alternative syntax ( if: / elseif: / endif; ) is common for templates, but arguably less easy to follow than normal { code } blocks. PHP的替代语法( if: / elseif: / endif; )在模板中很常见,但是可以说比普通的{ code }块不那么容易遵循。

  • 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 . 被遗忘的运算符,尤其是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. 您始终可以查看损坏的和上一个工作版本的diff 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. 不可见的杂散Unicode字符 :在某些情况下,您需要在源文件上使用十六进制编辑器或其他编辑器/查看器。 Some problems cannot be found just from looking at your code. 仅查看代码无法发现某些问题。

  • Take care of which type of linebreaks are saved in files. 请注意将哪种换行符保存在文件中。

    • PHP just honors \\n newlines, not \\r carriage returns. PHP只接受\\ n换行符,而不接受\\ r回车符。

    • Which is occasionally an issue for MacOS users (even on OS X for misconfigured editors). 对于MacOS用户,这有时是个问题(即使在OS X上,对于配置错误的编辑器)。

    • 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). 或者您的代码包含不可见的杂散Unicode(请参见上文)。 You can easily find out: Just copy your code back from the web form into your text editor. 您可以轻松地找到:只需将代码从Web表单复制回文本编辑器即可。

  • Check your PHP version . 检查您的PHP版本 Not all syntax constructs are available on every server. 并非所有语法构造在每台服务器上都可用。

    • php -v for the command line interpreter php -v用于命令行解释器

    • <?php phpinfo(); for the one invoked through the webserver. 用于通过Web服务器调用的服务器。


    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. 不要将PHP的保留关键字用作函数/方法,类或常量的标识符。

  • 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). 语法符号不是那么容易搜索(堆栈溢出本身由SymbolHound索引)。 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. 通常在您的php.ini ,或者通过.htaccess用于mod_php,甚至.user.ini带有FastCGI设置的.user.ini

Enabling it within the broken script is too late because PHP can't even interpret/run the first line. 在损坏的脚本中启用它为时已晚,因为PHP甚至无法解释/运行第一行。 A quick workaround is crafting a wrapper script, say test.php : 一种快速的解决方法是设计包装器脚本,例如test.php

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

Then invoke the failing code by accessing this wrapper script. 然后通过访问此包装脚本来调用失败的代码。

It also helps to enable PHP's error_log and look into your webserver's error.log when a script crashes with HTTP 500 responses. 当脚本因HTTP 500响应而崩溃时,它还有助于启用PHP的error_log并查看Web服务器的error.log


#3楼

Unexpected T_VARIABLE 意外的T_VARIABLE

An "unexpected T_VARIABLE " means that there's a literal $variable name, which doesn't fit into the current expression/statement structure. “意外的T_VARIABLE ”表示存在一个文字$variable名称,该名称不适合当前的表达式/语句结构。

有目的的抽象/不精确运算符+ $变量图

  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. PHP无法在此处猜测变量是否应该添加,减去或比较等。

  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 ; 等效你有看到这个listglobal陈述,或缺乏时; semicolon in a for loop. for循环中的分号。

  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"}(); 在这种情况下,使用$this->{"myFunc$VAR"}();进行可变属性查找$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 parens after language constructs 语言构造后缺少括号

    Hasty typing may lead to forgotten opening parenthesis for if and for and foreach statements: 匆忙键入可能会导致ifforforeach语句的开头括号被遗忘:

      ⇓ 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 . 解决方案:从else除去条件或使用elseif

  9. Need brackets for closure 需要括号关闭

      ⇓ function() uses $var {} 

    Solution: Add brackets around $var . 解决方案:在$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: 如在“不可见的杂散Unicode”(例如, 不间断的空格 )的参考答案中所提到的,对于诸如以下这样的无意代码,您可能还会看到此错误:

     <?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. 如果您的代码在视觉上似乎没有包含语法问题,请与hexeditor一起检查。

See also 也可以看看


#4楼

Unexpected T_STRING 意外的T_STRING

T_STRING is a bit of a misnomer. T_STRING有点用词不当。 It does not refer to a quoted "string" . 它不引用带引号的"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. 范围从bare字到剩余的CONSTANT或函数名,忘记的未加引号的字符串或任何纯文本。

  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. 为方便起见,在输出带有双引号的纯HTML时,应首选外部单引号。
    • 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. 为了获得更长的输出,最好使用多条echo / print线,而不是转入和移出。 Better yet consider a HEREDOC section. 最好还是考虑HEREDOC部分。

    See also What is the difference between single-quoted and double-quoted strings in PHP? 另请参见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_STRING s which the parser may protest then. 解析器随后可能会抗议的不只是文字T_STRING Another frequent variation is an Unexpected '>' for unquoted literal HTML. 另一个常见的变体是未引用文字HTML的Unexpected '>'

  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: 印刷引号不是 PHP期望的:

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

    Typographic/smart quotes are Unicode symbols. 印刷/智能引号是Unicode符号。 PHP treats them as part of adjoining alphanumeric text. PHP将它们视为相邻的字母数字文本的一部分。 For example ”these is interpreted as a constant identifier. 例如, ”these被解释为常量标识符。 But any following text literal is then seen as a bareword/T_STRING by the parser. 但是随后的任何文本文字都会被解析器视为裸字/ T_STRING。

  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 || PHP只是不知道您是要一个接一个地运行两个函数,还是要乘以它们的结果,相加,比较它们,还是只运行一个|| or the other. 或其他。

  5. Short open tags and <?xml headers in PHP scripts 简短的打开标记和PHP脚本中的<?xml标头

    This is rather uncommon. 这是相当罕见的。 But if short_open_tags are enabled, then you can't begin your PHP scripts with an XML declaration : 但是,如果启用了short_open_tags,则无法以XML声明开始PHP脚本:

      ⇓ <?xml version="1.0"?> 

    PHP will see the <? PHP会看到<? and reclaim it for itself. 并自行回收。 It won't understand what the stray xml was meant for. 它不明白流浪xml是什么意思。 It'll get interpreted as constant. 它将被解释为常量。 But the version will be seen as another literal/constant. 但是该version将被视为另一个文字/常量。 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 不可见的Unicode字符

    A most hideous cause for syntax errors are Unicode symbols, such as the non-breaking space . 语法错误最可怕的原因是Unicode符号,例如不间断的space PHP allows Unicode characters as identifier names. PHP允许将Unicode字符用作标识符名称。 If you get a T_STRING parser complaint for wholly unsuspicious code like: 如果您收到T_STRING解析器投诉,涉及完全不可疑的代码,例如:

     <?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. 基于Java的IDE有时会忽略UTF-8 BOM表,零宽度空格,段落分隔符等问题。请尝试重新编辑所有内容,删除空格并重新添加正常空格。

    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. 反过来,这会使PHP发出有用的通知。

  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. PHP中的变量用美元符号表示,后跟变量名称。

    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.). 当PHP代码从用另一种语言 (C,Java,JavaScript等) 编写的代码“转换”时,这是一个常见错误。 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\\''; 例如: echo 'Jim said \\'Hello\\''; will print Jim said 'hello' 将打印Jim said 'hello'

    If you escape the closing quote of a string, the closing quote will be taken literally and not as intended, ie 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. 在Windows中指定路径时,非常常见的错误: "C:\\xampp\\htdocs\\"是错误的。 You need "C:\\\\xampp\\\\htdocs\\\\" . 您需要"C:\\\\xampp\\\\htdocs\\\\"


#5楼

Unexpected T_CONSTANT_ENCAPSED_STRING 意外的T_CONSTANT_ENCAPSED_STRING
Unexpected T_ENCAPSED_AND_WHITESPACE 意外的T_ENCAPSED_AND_WHITESPACE

The unwieldy names T_CONSTANT_ENCAPSED_STRING and T_ENCAPSED_AND_WHITESPACE refer to quoted "string" literals . 笨拙的名称T_CONSTANT_ENCAPSED_STRINGT_ENCAPSED_AND_WHITESPACE引用带引号的"string" 文字

They're used in different contexts, but the syntax issue are quite similar. 它们在不同的上下文中使用,但是语法问题非常相似。 T_ENCAPSED… warnings occur in double quoted string context, while T_CONSTANT… strings are often astray in plain PHP expressions or statements. T_ENCAPSED…警告在双引号字符串上下文中发生,而T_CONSTANT…字符串通常在纯PHP表达式或语句中误入歧途。

  1. Incorrect variable interpolation 变量插值错误

    And it comes up most frequently for incorrect PHP variable interpolation: 对于错误的PHP变量插值,它最常出现:

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

    Quoting arrays keys is a must in PHP context. 在PHP上下文中,必须引用数组键。 But in double quoted strings (or HEREDOCs) this is a mistake. 但是在双引号字符串(或HEREDOC)中,这是一个错误。 The parser complains about the contained single quoted 'string' , because it usually expects a literal identifier / key there. 解析器抱怨所包含的单引号'string' ,因为它通常期望在那里使用文字标识符/键。

    More precisely it's valid to use PHP2-style simple syntax within double quotes for array references: 更准确地说, 数组引用的双引号中使用PHP2样式的简单语法是有效的:

     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. 更好的IDE实际上为此使用了不同的语法着色。

  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: 如果字符串在表达式之后,但是没有串联或其他运算符,那么您将看到PHP抱怨字符串文字:

      ⇓ 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. 虽然对您我来说都很明显,但是PHP只是无法猜测该字符串是否应该附加到该字符串中。

  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. 但是,双引号也注定用于HTML属性。 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. 提示 :将编辑器/ IDE设置为对单引号和双引号字符串使用略有不同的颜色。 (It also helps with application logic to prefer eg 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: 相反,只需对HTML属性的引号使用正确的\\"转义符:

     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. 尽管这也可能导致语法混乱,但是所有更好的IDE /编辑器都会通过对转义的引号进行不同的着色来再次提供帮助。

  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. 在这里, ', '将成为裸词之后的字符串文字,而显然login本来是一个字符串参数。

  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 功能参数列表

    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. 在这里,PHP抱怨两个字符串文字彼此紧随其后。 But the real cause is the unclosed previous string of course. 但是,真正的原因当然是之前未公开的字符串。

See also 也可以看看


#6楼

Unexpected ( 意外的(

Opening parentheses typically follow language constructs such as if / foreach / for / array / list or start an arithmetic expression. 括号通常遵循以下语言结构,例如if / foreach / for / array / list或开始算术表达式。 They're syntactically incorrect after "strings" , a previous () , a lone $ , and in some typical declaration contexts. "strings" ,previous () ,lone $和某些典型的声明上下文中,它们在语法上不正确。

  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: 即使在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. 与函数调用不同,在函数调用中,您可以自由使用whatever(1+something()*2)等。

  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? 另请参见为什么PHP属性不允许功能?

    Again note that PHP 7 only allows var $xy = 1 + 2 +3; 再次注意,PHP 7仅允许var $xy = 1 + 2 +3; constant expressions there. 常量表达式。

  3. JavaScript syntax in PHP PHP中的JavaScript语法

    Using JavaScript or jQuery syntax won't work in PHP for obvious reasons: 出于明显的原因,在JavaScript中无法使用JavaScript或jQuery语法

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

    When this happens, it usually indicates an unterminated preceding string; 发生这种情况时,通常表示前一个未终止的字符串。 and literal <script> sections leaking into PHP code context. 和文字<script>部分泄漏到PHP代码上下文中。

  4. isset(()), empty, key, next, current isset(()),空,键,下一个,当前

    Both isset() and empty() are language built-ins, not functions. isset()empty()都是语言内置的,而不是函数。 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. PHP预期值还有正是如此抱怨早期闭合)括号。

      ⇓ callfunc(1, 2, ); 

    A trailing comma is only allowed in array() or list() constructs. 仅在array()list()构造中允许使用逗号结尾。

  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 Foreach constant

    For forgotten variable $ prefixes in control statements you will see: 对于控制语句中被遗忘的变量$前缀,您将看到:

      ↓ ⇓ foreach ($array as wrong) { 

    PHP here sometimes tells you it expected a :: instead. PHP有时会告诉您它期望使用::代替。 Because a class::$variable could have satisfied the expected $variable expression.. 因为class :: $ variable可以满足预期的$ variable表达式。


Unexpected { 意外{

Curly braces { and } enclose code blocks. 花括号{}包含代码块。 And syntax errors about them usually indicate some incorrec nesting. 而且关于它们的语法错误通常表明有些不正确的嵌套。

  1. Unmatched subexpressions in an if 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 parens or use an IDE which helps with that. 数数您的父母或使用IDE可以帮助您。 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 grammer: 如果您将括号和花括号弄混了,它将不符合语言语法:

      ⇓ $var = 5 * {7 + $x}; 

    There are a few exceptions for identifier construction, such as local scope variable ${references} . 标识符构造有一些例外,例如局部范围变量${references}

  3. Variable variables or curly var expressions 可变变量或卷曲var表达式

    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; 在这里,解析器无法判断您是否仍想添加+ 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. 在以上代码段中, if没有开口{大括号。 Thus the closing } one below became redundant. 因此,下面的结尾}变得多余。 And therefore the next closing } , which was intended for the function, was not associatable to the original opening { curly brace. 因此,下一个用于此功能的结束符}与原始开口{花括号不相关。

    Such errors are even harder to find without proper code indentation. 如果没有适当的代码缩进,则更难发现此类错误。 Use an IDE and bracket matching. 使用IDE和括号匹配。


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没有条件

      ⇓ if { } 

    Which doesn't make sense, obviously. 显然,这没有意义。 The same thing for the usual suspects, for / foreach , while / do , etc. 对于通常的犯罪嫌疑人, for / foreachwhile / do等,也是一样。

    If you've got this particular error, you definitely should look up some manual examples. 如果遇到此特定错误,则绝对应该查看一些手动示例。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值