Blog coding and discussion of coding about JavaScript, PHP, CGI, general web building etc.

Sunday, January 24, 2016

PHP Parse/Syntax Errors; and How to solve them?

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  

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.

Answer by mario for PHP Parse/Syntax Errors; and How to solve them?


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.

function definition syntax abstract

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.

    Expected: semicolon

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

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.

Answer by mario for PHP Parse/Syntax Errors; and How to solve them?


Unexpected T_VARIABLE

An "unexpected T_VARIABLE" means that there's a literal $variable name, which doesn't fit into the current expression/statement structure.

purposefully abstract/inexact operator+$variable diagram

  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.

  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 ; semicolon in a for loop.

  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"}(); 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:

           ?  foreach $array as $key) {  

    Solution: add the missing opening ( between statement and variable.

See also

Answer by mario for PHP Parse/Syntax Errors; and How to solve them?


Unexpected T_STRING

T_STRING is a bit of a misnomer. It does not refer to a quoted "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.

  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 "click here";  

    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.
    • 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. Better yet consider a HEREDOC section.

    See also What is the difference between single-quoted and double-quoted strings in 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_STRINGs which the parser may protest then. Another frequent variation is an Unexpected '>' for unquoted literal HTML.

  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:

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

    Typographic/smart quotes are Unicode symbols. PHP treats them as part of adjoining alphanumeric text. For example ?these is interpreted as constant identifier. But any following text literal is then seen as bareword/T_STRING by the parser.

  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 || or the other.

  5. Short open tags and headers in php scripts

    This is rather uncommon. But if short_open_tags are enabled, then you can't begin your PHP scripts with an XML declaration:

          ?    

    PHP will see the and reclaim it for itself. It won't understand what the stray xml was meant for. It'll get interpreted as constant. But the version will be seen as another literal/constant. 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

    A most hideous cause for syntax errors are Unicode symbols, such as the non-breaking space. PHP allows Unicode characters as identifier names. If you get a T_STRING parser complaint for wholly unsuspicious code like:

    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.

    You can narrow it down with with adding redundant ; statement separators at each line start:

    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.

Answer by mario for PHP Parse/Syntax Errors; and How to solve them?


Unexpected T_CONSTANT_ENCAPSED_STRING
Unexpected T_ENCAPSED_AND_WHITESPACE

The unwieldy names T_CONSTANT_ENCAPSED_STRING and T_ENCAPSED_AND_WHITESPACE refer to quoted "string" literals.

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.

  1. Incorrect variable interpolation

    And it comes up most frequently for incorrect PHP variable interpolation:

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

    Quoting arrays keys is a must in PHP context. But in double quoted strings (or HEREDOCs) this is a mistake. The parser complains about the contained single quoted 'string', because it usually expects a literal identifier / key there.

    More precisely it's valid to use PHP2-style simple syntax within double quotes for array references:

    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.

  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:

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

  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 "click here";        ????????????????????????????????????????  

    That example started with double quotes. But double quotes were also destined for the HTML attributes. 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. (It also helps with application logic to prefer e.g. 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:

    print "click here";  

    While this can also lead to syntax confusion, all better IDEs/editors again help by colorizing the escaped quotes differently.

  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.

  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. But the real cause is the unclosed previous string of course.

See also

Answer by mario for PHP Parse/Syntax Errors; and How to solve them?


Unexpected (

Opening parentheses typically follow language constructs such as if/foreach/for/array/list or start an arithmetic expression. They're syntactically incorrect after "strings", a previous (), a lone $, and in some typical declaration contexts.

  1. Function declaration parameters

    A rarer occurence for this error is trying to use expressions as default function parameters. This is not supported, even in 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.

  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?

    Again note that PHP 7 only allows var $xy = 1 + 2 +3; constant expressions there.

  3. Javascript syntax in PHP

    Utilizing Javascript or jQuery syntax won't work in PHP for obvious reasons:

    When this happens, it usually indicates an unterminated preceding string; and literal

0 comments:

Post a Comment

Popular Posts

Powered by Blogger.