PHP解析/语法错误;以及如何解决它们 [英] PHP parse/syntax errors; and how to solve them

查看:114
本文介绍了PHP解析/语法错误;以及如何解决它们的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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:

意外的T_VARIABLE
意外的'$ varname'(T_VARIABLE)

意外的T_CONSTANT_ENCAPSED_STRING
意外的T_ENCAPSED_AND_WHITESPACE

意外的$ end

意外的T_FUNCTION

意外{
意外}
意外(
意外)

意外的[
意外的]

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

意外的T_LNUMBER

意外?

意外的继续(T_CONTINUE)
意外的继续(T_BREAK)
意外的继续(T_RETURN)

意外的'='

意外的T_INLINE_HTML

意外的T_PAAMAYIM_NEKUDOTAYIM

意外的T_OBJECT_OPERATOR

意外的T_DOUBLE_ARROW

意外的T_SL

意外的T_BOOLEAN_OR
意外的T_BOOLEAN_AND

意外的T_IS_EQUAL
意外的T_IS_GREATER_OR_EQUAL
意外的T_IS_IDENTICAL
意外的T_IS_NOT_EQUAL
意外的T_IS_NOT_IDENTICAL
意外的T_IS_SMALLER_OR_EQUAL
意外<
意外的>

Unexpected T_IS_EQUAL
Unexpected T_IS_GREATER_OR_EQUAL
Unexpected T_IS_IDENTICAL
Unexpected T_IS_NOT_EQUAL
Unexpected T_IS_NOT_IDENTICAL
Unexpected T_IS_SMALLER_OR_EQUAL
Unexpected <
Unexpected >

意外的T_NS_SEPARATOR

输入中出现意外字符:"\" (ASCII = 92)状态= 1

Unexpected character in input: '\' (ASCII=92) state=1

意外的"public"(T_PUBLIC)
意外的私人"(T_PRIVATE)
意外的受保护"(T_PROTECTED)
意外的最终"(T_FINAL)

意外的T_STATIC

意外的T_CLASS

意外的T_DNUMBER

意外的, (逗号)

未受感染的. (期间)

意外的; (分号)

意外的* (星号)

意外的: (冒号)

意外的& (通话时间按引用)

Unexpected & (call-time pass-by-reference)

意外.

密切相关的参考文献:

  • 此错误在PHP中意味着什么? (运行时错误)
    • What does this error mean in PHP? (runtime errors)
      • Parse error: syntax error, unexpected T_XXX
      • Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE
      • Parse error: syntax error, unexpected T_VARIABLE

      并且:

      • The PHP manual on php.net and its various language tokens
      • Or Wikipedia's syntax introduction on PHP.
      • And lastly our php tag-wiki of course.

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

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

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

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

      If your browser displays error messages such as "SyntaxError: illegal character", then it's not actually php-related, but a javascript-syntax error.

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

      Syntax errors raised on vendor code: Finally, consider that if the syntax error was not raised by editing your codebase, but after an external vendor package install or upgrade, it could be due to PHP version incompatibility, so check the vendor's requirements against your platform setup.

      推荐答案

      语法错误是什么?

      PHP属于 C风格

      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.

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

      There are a few basic precautions you can always take:

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

      • Use proper code indentation, or adopt any lofty coding style. Readability prevents irregularities.

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

      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.

      典型的语法错误消息为:

      A typical syntax error message reads:

      解析错误:语法错误,意外的 T_STRING ,在行上的 file.php 中预期为';' strong> 217

      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.

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

      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.

      有很多方法可以缩小和修复语法问题.

      There are many approaches to narrow down and fix syntax hiccups.

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

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

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

      通常,您还需要查看前几行.

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

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

      查看语法着色

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

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

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

      Whitespace is your friend. Follow any coding style.

      暂时中断长行.

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

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

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

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

      在之间添加换行符:

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

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

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

      注释掉违规代码.

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

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

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

      • 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的替代语法(if:/elseif:/endif;)在模板中很常见,但是可以说比普通的{代码}块不那么容易理解.

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

      最常见的新人错误是:

      • 缺少用于终止语句/行的分号;.

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

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

      被遗忘的运算符,尤其是对于字符串.串联.

      Forgotten operators, in particular for the string . concatenation.

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

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

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

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

      • 如果您解决了一个问题,但在下面的某些代码中发现了其他问题,那么您基本上处于正确的道路上.

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

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

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

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

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

      • 采用源代码版本控制系统.您始终可以查看损坏的最后工作版本的diff.关于语法问题,这可能是有启发性的.
      • 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.

      不可见的Unicode杂散字符:在某些情况下,您需要

      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.

      特别是BOM,零宽度空格或不间断空格以及智能引号可以定期在源代码中找到它们.

      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仅接受 \ n 换行符,而不接受 \ r 回车符.

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

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

      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!

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

      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.

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

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

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

      <?php phpinfo();表示通过网络服务器调用的那个.

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

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

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

      试错是您的最后选择.

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

      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.

      更多指南:

      • PHP Debugging Basics by David Sklar
      • Fixing PHP Errors by Jason McCreary
      • PHP Errors – 10 Common Mistakes by Mario Lurig
      • Common PHP Errors and Solutions
      • How to Troubleshoot and Fix your WordPress Website
      • A Guide To PHP Error Messages For Designers - Smashing Magazine

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

      If your website is just blank, then typically a syntax error is the cause. Enable their display with:

      • error_reporting = E_ALL
      • display_errors = 1
      • error_reporting = E_ALL
      • display_errors = 1

      通常在您的 php.ini 中,或通过 .htaccess for mod_php, 甚至使用FastCGI设置 .user.ini .

      In your php.ini generally, or via .htaccess for mod_php, or even .user.ini with FastCGI setups.

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

      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.

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

      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.

      这篇关于PHP解析/语法错误;以及如何解决它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆