PHP解析/语法错误和如何解决他们? [英] PHP Parse/Syntax Errors; and How to solve them?

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

问题描述

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


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


意想不到的符号并不总是真正的罪魁祸首。但是行号给出一个粗略的想法,从哪里开始寻找。


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


尽管不是每种情况都与其他匹配。但是有一些的编辑器。

这也有助于括号/括号平衡。 p>


  • 阅读手册中的语言参考和示例。

    两次,变得有点精通。




  • 如何解释解析器错误?



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


    解析错误:语法错误,意外 T_STRING ,期望 c file.php strong>行


    哪些列出了可能的位置的语法错误。请参阅上述文件名行号



    A 昵称,例如 T_STRING 解释解析器/标记器最终无法处理的符号。这不一定是语法错误的原因。



    重要的是查看以前的代码行。通常,语法错误只是早期发生的事故。错误行号就是解析器最终放弃处理的地方。



    解决语法错误



    有很多方法可以缩小和修正语法呃嗝。




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




      • 对于失控的字符串和错放的操作符,这通常是你找到罪魁祸首。


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



    • 更准确地说,您还需要查看前面的行




      • 在上一行结束/语句中缺少; 分号。 (至少从风格的角度来看)


      • 如果 {代码块 } 未正确关闭或嵌套,您可能需要进一步调查源代码。使用正确的代码缩写来简化。



    • >语法着色




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


      • 运算符 + - * /。应该被着色不同。否则它们可能在错误的上下文中。


      • 如果您看到字符串颜色扩展太远或太短,那么您发现一个未转义或缺少关闭'字符串标记。


      • 通常操作者是孤独的,如果不是 ++ - 或圆括号在操作符之后,两个直接相互关联的字符串/标识符在大多数情况下是不正确的。



    • 空格是你的朋友

      按照任何编码风格。


    • 暂时分解长线。




      • 您可以随意添加换行符操作符或常量和字符串,然后解析器将对行号进行解析以解析错误,而不是查看非常冗长的代码,您可以隔离丢失或放错的语法


      • 如果语句分为不同或嵌套的条件,则将复杂的分解。

        / li>
      • 代替冗长的数学公式或逻辑链,使用临时变量来简化代码。 (更可读=更少的错误。)


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


          <您可以轻松识别代码
        1. 您不确定的部分

        2. 解析器抱怨的行。

        分区长码块真的有助于查找语法错误的起源。



    • 注释违规代码




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


      • 一旦你摆脱了解析错误,你就发现了问题源。稍微看一下。


      • 有时你想暂时删除完整的功能/方法块。 (如果不匹配的大括号和错误的缩进代码)。


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



    • 新手避免一些令人困惑的语法结构。




      • 三元? :条件运算符可以紧凑的代码,实际上是有用的。但是,它在所有情况下都不能帮助可读性。


      • PHP替代语法( if: if / elseif: / endif; )对于模板是常见的,但可以说不太容易遵循正常 {代码} 块。



    • 最流行的新手错误是:




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


      • 不匹配的的字符串引号'和未转义的引号。


      • 忘记的运算符,特别是字符串 concatenation。


      • 不平衡括号。在报告的行中计算他们的数量是否相等?



    • 不要忘记解决一个语法问题可以揭示下一个。




      • 如果你让一个问题消失,但另一个问题我就出现了在下面的一些代码中,你主要是在正确的路径。


      • 如果在编辑一个新的语法错误后,同样的行,可能是一个失败。 (不总是。)



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




      • 采用源代码版本控制系统。您可以随时查看破损和上一个工作版本的 diff 。哪些语法问题可能是有启发性的。





    • 不可见的流浪unicode字符:在某些情况下,您需要使用hexeditor 或不同的编辑器/查看器。某些问题只能从查看代码中找到。




    • 保存文件中保存的换行类型 。 PHP只是荣誉 \\\
      换行符,而不是 \r 回车。这对MacOS用户来说偶尔也是一个问题(即使在OS X上配置错误的编辑器)。


    • 检查您的 PHP版本。并不是所有的语法结构在每个服务器上都可用。


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


    • 试验和错误是你的最后的手段。




    如果所有其他失败,您总是可以 google 语法符号不是很容易搜索(Stack Overflow本身由 SymbolHound 索引)。因此,在找到相关内容之前,可能需要再浏览几页。



    进一步的指导:





    死亡白屏



    如果您的网站只是空白,则通常会出现语法错误。

    启用其显示:




    • error_reporting = E_ALL

    • display_errors = 1



    在你的 php.ini 一般来说,
    或通过 .htaccess for 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 并查看您的 webservers error.log


    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 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 Stackoverflow is also welcoming rookie coders, it's mostly targetted at professional programming questions.

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

    解决方案

    What are 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 parens/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 regularily you need to look at preceding lines as well.

      • In particular missing ; semicolons are missing at the previous line end / 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 indendation to simplify that.

    • Look at the syntax colorization !

      • Strings and variables and constants should all have different colors.

      • Operators +-*/. should be 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 -- 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 concretise the line number for parsing errors. Instead of looking at 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 = less errors.)

      • Add newlines between:

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

      • PHPs 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 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 another 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 first measure to find non-ASCII symbols.

      • In particular BOMs, zero-width spaces, or non-breaking spaces, and smart quotes regularily can find their way into 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).

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

    • Don't use PHPs 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 PHPs error_log and look into your webservers error.log when a script crashes with HTTP 500 responses.

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

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