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

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

问题描述

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

<块引用>

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

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

<块引用>

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

虽然不是每个案例都匹配另一个.然而,有一些,带有语法高亮.这也有助于括号/括号平衡.

  • 阅读手册中的语言参考和示例.两次,以达到一定程度.

  • 如何解释解析器错误

    典型的语法错误信息如下:

    <块引用>

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

    其中列出了语法错误的可能位置.查看提到的文件名行号.

    moniker,例如 T_STRING 解释了解析器/令牌生成器无法识别的符号最后处理.然而,这不一定是语法错误的原因.

    查看之前的代码行也很重要.通常语法错误只是之前发生的不幸.错误行号正是解析器最终放弃处理它的地方.

    解决语法错误

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

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

      • 对于失控的字符串和错位的运算符,这通常是您找到罪魁祸首的地方.

      • 从左到右阅读这行,想象每个符号的作用.

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

      • 特别是,缺少 ; 分号在前一行结尾/语句处丢失.(至少从文体的角度来看是这样.)

      • 如果 { 代码块 } 被错误地关闭或嵌套,您可能需要进一步调查源代码.使用适当的代码缩进来简化它.

    • 看看语法着色

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

      • 运算符 +-*/. 也应该着色.否则他们可能处于错误的上下文中.

      • 如果您看到字符串着色延伸得太远或太短,那么您发现了一个未转义或丢失的结束 "' 字符串标记.

      • 两个相同颜色的标点符号彼此相邻也可能意味着麻烦.通常,如果运算符后面不是 ++-- 或括号,则运算符是单独的.在大多数情况下,两个直接紧随其后的字符串/标识符是不正确的.

    • 空白是你的朋友.遵循任何编码风格.

    • 暂时中断排长队.

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

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

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

      • 在以下内容之间添加换行符:

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

        对长代码块进行分区确实有助于定位语法错误的根源.

    • 注释有问题的代码.

      • 如果您无法隔离问题源,请开始注释(从而暂时删除)代码块.

      • 一旦你摆脱了解析错误,你就找到了问题的根源.仔细看看那里.

      • 有时您想暂时删除完整的函数/方法块.(在不匹配的大括号和错误缩进代码的情况下.)

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

    • 作为新手,请避免一些令人困惑的语法结构.

      • 三元?: 条件运算符可以压缩代码,确实很有用.但这并不有助于所有情况下的可读性.不了解时更喜欢简单的 if 语句.

      • PHP 的替代语法(if:/elseif:/endif;)在模板中很常见,但可以说不太容易遵循比普通{代码}块.

    • 最常见的新手错误是:

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

      • "' 的不匹配字符串引号和其中的未转义引号.

      • 被遗忘的运算符,特别是对于字符串 . 连接.

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

    • 不要忘记解决一个语法问题可以发现下一个.

      • 如果您解决了一个问题,但在下面的某些代码中又出现了其他问题,那么您基本上走对了路.

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

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

      • 采用源代码版本控制系统.您始终可以查看损坏的和上次工作版本的 diff.这可能对语法问题有启发意义.
    • 不可见的杂散 Unicode 字符:在某些情况下,您需要在您的源代码上使用十六进制编辑器 或不同的编辑器/查看器.有些问题光看你的代码是查不出来的.

    • 注意保存在文件中的换行符类型.

      • PHP 只支持 换行符,而不是 回车.

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

      • 当使用单行 //# 注释时,它通常只会作为一个问题出现.当换行符被忽略时,多行 /*...*/ 注释很少干扰解析器.

    • 如果您的语法错误未通过网络传播:碰巧您的机器上有语法错误.但是在线发布完全相同的文件不再显示它.这只能意味着两件事之一:

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

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

    • 检查您的PHP 版本.并非所有的语法结构都适用于每台服务器.

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

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


      这些不一定相同.尤其是在使用框架时,您会将它们匹配起来.

    • 不要使用 PHP 的保留关键字作为函数/方法、类的标识符或常量.

    • 反复试验是您最后的手段.

    如果所有其他方法都失败了,您可以随时google您的错误消息.语法符号并不容易搜索(不过,堆栈溢出本身由 SymbolHound 索引).因此,您可能需要多浏览几页才能找到相关内容.

    更多指南:

    白屏死机

    如果您的网站是空白的,那么通常是因为语法错误.启用他们的显示:

    • error_reporting = E_ALL
    • display_errors = 1

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

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

    然后通过访问这个包装脚本来调用失败的代码.

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

    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.

    解决方案

    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 newlines, not 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.

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

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