PHP parsing/syntax errors; and how to resolve them
P粉633075725
P粉633075725 2023-08-23 16:16:57
0
2
618
<p>Everyone encounters grammar errors. Even experienced programmers make mistakes. For newcomers, this is just part of the learning process. However, error messages are usually easy to interpret, for example: </p> <blockquote> <p>PHP parsing error: Syntax error, unexpected '{' in index.php line 20</p> </blockquote> <p>Unexpected symbols aren't always the real culprit. But the line number gives a rough idea of ​​where to start looking. </p> <blockquote> <p>Always look at the <strong>code context</strong>. Syntax errors are often hidden in <em> or </em> mentioned in <strong>the preceding line of code</strong>. Compare your code to the syntax examples in the manual. </p> </blockquote> <p>Although not all cases match each other. However, there are some general steps for <strong>resolving syntax errors</strong>.This reference summarizes common pitfalls: </p> <ul> <li><p>Unexpected T_STRING</p> </li> <li><p>Unexpected T_VARIABLE </p><p> Unexpected '$varname' (T_VARIABLE)</p> </li> <li><p>Unexpected T_CONSTANT_ENCAPSED_STRING </p><p>Unexpected T_ENCAPSED_AND_WHITESPACE</p> </li> <li><p>Unexpected $end</p> </li> <li><p>Unexpected T_FUNCTION...</p> </li> <li><p>Unexpected<code>{</code></p><p>Unexpected<code>}</code></p><p> Unexpected<code>(</code></p><p>Unexpected<code>)</code></p> </li> <li><p>Unexpected<code>[</code></p><p>Unexpected<code>]</code></p> </li> <li><p>Unexpected T_IF </p><p> Unexpected T_FOREACH </p><p> Unexpected T_FOR </p><p> Unexpected T_WHILE </ p><p> Unexpected T_DO </p><p> Unexpected T_PRINT </p><p> Unexpected T_ECHO</p> </li> <li><p>Unexpected T_LNUMBER</p> </li> <li><p>Accident?</p> </li> <li><p>Unexpected continuation (T_CONTINUE)</p><p>Unexpected continuation (T_BREAK)</p><p>Unexpected continuation (T_RETURN)</p> </li> <li><p>Unexpected "="</p> </li> <li><p>Unexpected T_INLINE_HTML…</p> </li> <li><p>Unexpected T_THIS_IS_THE_THING...</p> </li> <li><p>Unexpected T_OBJECT_OPERATOR...</p> </li> <li><p>Unexpected T_DOUBLE_ARROW...</p> </li> <li><p>Unexpected T_SL...</p> </li> <li><p>Unexpected T_BOOLEAN_OR… </p><p> Unexpected T_BOOLEAN_AND…</p> </li> <li><p>Unexpected T_IS_EQUAL </p><p> Unexpected T_IS_GREATER_OR_EQUAL </p><p> Unexpected T_IS_IDENTICAL </p><p> Unexpected T_IS_NOT_EQUAL </p><p> Unexpected T_IS_NOT_IDENTICAL </p><p> Unexpected T_IS_SMALLER_OR_EQUAL </p><p> Unexpected <code><</code> </p><p> Unexpected <code>></code></p> </li> <li><p>Unexpected T_NS_SEPARATOR...</p> </li> <li><p>Unexpected characters in input: '<code></code>' (ASCII=92) state=1</p> </li> <li><p>Unexpected 'Public' (T_PUBLIC) </p><p>Unexpected 'Private' (T_PRIVATE) </p><p>Unexpected 'Protected' (T_PROTECTED ) </p><p>Unexpected 'T_FINAL'...</p> </li> <li><p>Unexpected T_STATIC...</p> </li> <li><p>Unexpected T_CLASS…</p> </li> <li><p>Unexpected 'use' (T_USE)</p> </li> <li><p>Unexpected T_DNUMBER</p> </li> <li><p>Unexpected <code>,</code> <em>(comma)</em></p> </li> <li><p>Unexpected<code>.</code> <em>(period)</em></p> </li> <li><p>Unexpected <code>;</code> <em>(semicolon)</em></p> </li> <li><p>Unexpected<code>*</code><em> (asterisk)</em></p> </li> <li><p>Unexpected<code>: </code><em> (colon)</em></p> </li> <li><p>Unexpected ':', expected ',' or ')'</p> </li> <li><p>Unexpected<code>&</code> (passed by reference when called)</p> </li> <li><p>Unexpected<code>. </code></p> </li> </ul> <p>Related references:</p> <ul> <li>What does this error mean in PHP? (runtime error) <ul> <li>Parse error: syntax error, unexpected T_XXX</li> <li>Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE</li> <li>Parse error: syntax error, unexpected T_VARIABLE</li> </ul> </li> <li>What does this symbol mean in PHP? (language tag)</li> <li>Those<code>""</code>smart<code>''</code>quotes mean nothing to PHP</li> </ul> <p>Also:</p> <ul> <li>PHP manual and its various language tags at php.net</li> <li>Or Wikipedia’s syntax introduction to PHP. </li> <li>Finally, of course, is our <strong>php</strong> tag wiki. </li> </ul> <p>Although Stack Overflow welcomes novice programmers, it is primarily geared toward professional programming questions. </p> <ul> <li>Answer everyone's coding errors and narrow spelling errors that are mostly considered off-topic. </li> <li>So before posting a syntax fix request, please take some time to follow the basic steps. </li> <li>If you still need to do this, show your own solution, attempted fix, and your thought process for what appears to be an error or what might be an error.</li> </ul> <p>If your <em>Browser</em> displays an error message such as "SyntaxError: illegal character", then it is not actually php related, but a javascript syntax error. </p> <hr /> <p><strong>Syntax errors raised by vendor code:</strong>Finally, consider that if the syntax error is not raised by editing the code base, but instead is raised after an external vendor package is installed or upgraded , it may be an incompatibility due to PHP version, so please check the vendor's requirements against your platform settings. </p>
P粉633075725
P粉633075725

reply all(2)
P粉639667504

I think this topic is completely over discussed/overly complex. Using an IDE is a way to completely avoid any syntax errors. I would even say that working without an IDE is unprofessional. Why? Because modern IDEs check your syntax after every character you type. When you are coding and the entire line turns red and a big warning notification shows the exact type and exact location of the syntax error, then there is absolutely no need to search for other solutions.

Using syntax checking IDE means:

You'll (effectively) never encounter syntax errors again because you'll see them correctly as you type. honestly.

Great IDEs with syntax checking (all available for Linux, Windows, and Mac):

  1. NetBeans [Free]
  2. PHPStorm [$199]
  3. Eclipse and PHP Plugin [Free]
  4. Sublime [$80] (Primarily a text editor but extendable with plugins such as PHP Grammar Parser)
P粉068510991

What is a syntax error?

PHP belongs to the C style and Imperative programming languages. It has strict syntax rules that cannot be recovered when a misplaced symbol or identifier is encountered. It cannot guess your coding intentions.

Most Important Tips

There are some basic precautions you can always take:

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

  • Use an IDE or editor for PHP with syntax highlighting. This also helps with bracket/bracket balance.

  • Read the language reference and examples in the manual. After two times, you become proficient.

How to interpret parser errors

Typical syntax error messages are as follows:

It lists possible syntax errors. See the filename and linenumber mentioned.

A name such as T_STRING explains the final handling of symbols that cannot be parsed by the parser/tokenizer. However, this is not necessarily the cause of the syntax error.

Looking at previous lines of code is also important. Often, syntax errors are just accidents that happened before. The error line number is exactly where the parser finally gives up processing everything.

Resolve syntax errors

There are many ways to narrow down and fix syntax issues.

  • Open the mentioned source file. Look at the lines of code mentioned.

    • With runaway strings and misplaced operators, this is usually where you find the culprit.

    • Read the line from left to right and imagine what each symbol does.

  • You also need to look at the preceding lines more often.

    • Specifically, the ; semicolon is missing at the end/statement of the previous line. (At least from a style standpoint.)

    • If {code blocks} are not closed or nested correctly, you may need to further investigate the source code. Use proper code indentation to simplify.

  • Look atGrammar Coloring!

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

    • Operators -*/. should also be colored differently. Otherwise they may be in the wrong environment.

    • If you find that the string coloring extends too far or too short, you have found an unescaped or missing ending " or ' string marker .

    • Two adjacent punctuation marks of the same color can also mean trouble. In general, an operator is alone if it is not followed by , --, or a parenthesis. In most cases, two directly connected strings/identifiers are incorrect.

  • Blank space is your friend. Follow any coding style.

  • Break the long queue temporarily.

    • You can freely add newlines between operators or constants and strings. The parser will then externalize the line number that parsed the error. Instead of looking at very verbose code, you can isolate missing or misplaced syntax symbols.

    • Split complex if statements into distinct or nested if conditions.

    • Instead of using lengthy mathematical formulas or logical chains, use temporary variables to simplify your code. (More readable = fewer errors.)

    • Add newlines between:

      1. You can easily identify the correct code,
      2. The part you are not sure about,
      3. and the line the parser complains about.

      Partitioning long code blocks does help locate the source of syntax errors.

  • Comment out the violating code.

    • If you can't isolate the source of the problem, start commenting out (thereby temporarily removing) blocks of code.

    • Once you resolve the parsing error, you have found the source of the problem. Take a closer look there.

    • Sometimes you want to temporarily remove a complete function/method block. (In case of mismatched braces and incorrectly indented code.)

    • When you can't solve the syntax problem, try starting from scratch rewriting the commented out part.

  • As a newbie, please avoid some confusing grammatical structures.

    • 三元? : Conditional operators can condense code and are really useful. But it doesn't improve readability in all situations. Prefer simple if statements in unfamiliar situations.

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

  • The most common mistakes made by novices are:

    • Missing semicolon terminating statement/line ;.

    • Mismatched string quotes for
    • " or ', where the quotes are not escaped.

    • Forgotten operators, especially string . concatenation.

    • Unbalanced(Brackets). Count them in the reported rows. Are their quantities equal?

  • Don’t forget that solving one grammar problem can reveal the next.

    • If you solve one problem, but something else appears in some of the code below, you're basically on the right track.

    • If a new syntax error appears on the same line after editing, your attempted change may fail. (But not always.)

  • If it cannot be repaired, please restore a backup of the previous working code.

    • Adopt source code version control system. You can always view the difference between the corrupted version and the last working version. It might help to understand what the syntax problem is.
  • Invisible Stray Unicode Characters: In some cases you will need to use a hex editor or other editor on the source code/ Viewer. Some problems cannot be found just by looking at the code.

  • Pay attention to the line break type saved in the file.

    • PHP only supports \n line feed characters, but not \r carriage return characters.

    • This can sometimes be a problem for MacOS users (even on OS X if the editor is misconfigured).

    • Usually problems only occur when using single-line // or # comments. Multiline /*...*/ comments rarely interfere with the parser when newlines are ignored.

  • If your syntax error is not transmitted over the network : You happen to have a syntax error on your machine. But posting the same file online no longer shows it. This can only mean one of two things:

    • You are viewing the wrong file!

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

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

    • php -v for command line interpreter

    • For calling via a web server.


    These are not necessarily the same. Especially when using frames, you need to match them up.

  • Do not use PHP’s reserved keywords as function/method, class identifiers or constants.

  • Trial and error is a last resort.

If all else fails, you can always google your error message. Syntax symbols are less easily searchable (although Stack Overflow itself is indexed by SymbolHound). Therefore, you may need to browse a few more pages to find relevant content.

More guides:

White screen of death

If your site is just blank, it's usually due to a grammatical error. Enable its display:

  • error_reporting = E_ALL
  • display_errors = 1

In your php.iniGenerally speaking, or via mod_php's .htaccess, Even .user.ini uses FastCGI settings.

It's too late to enable it in a broken script because PHP can't even interpret/run the first line. A quick fix is ​​to make a wrapper script like test.php:

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

The failing code is then called by accessing this wrapper script.

It also helps to enable PHP's error_log and view your web server's error.log when the script crashes with an HTTP 500 response.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!