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


everyone runs syntax errors. experienced programmers make typos. newcomers it's part of learning process. however, it's easy interpret error messages such as:

php parse error: syntax error, unexpected '{' in index.php on line 20

the unexpected symbol isn't real culprit. line number gives rough idea start looking.

always @ code context. syntax mistake hides in mentioned or in previous code lines. compare code against syntax examples manual.

while not every case matches other. yet there general steps solve syntax mistakes. references summarized common pitfalls:

closely related references:

and:

while stackoverflow welcoming rookie coders, it's targetted @ professional programming questions.

  • answering everyones coding mistakes , narrow typos considered off-topic.
  • so please take time follow basic steps, before posting syntax fixing requests.
  • if still have to, please show own solving initiative, attempted fixes, , thought process on looks or might wrong.

if browser displays error messages such "syntaxerror: illegal character", it's not -related, -syntax error.

what syntax errors?

php belongs c-style , imperative programming languages. has rigid grammar rules, cannot recover when encountering misplaced symbols or identifiers. can't guess coding intentions.

function definition syntax abstract

most important tips

there few basic precautions can take:

  • use proper code indentation, or adopt lofty coding style.
    readability prevents irregularities.

  • use ide or editor php syntax highlighting.
    parens/bracket balancing.

    expected: semicolon

  • read language reference , examples in manual.
    twice, become proficient.

how 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 possible location of syntax mistake. see mentioned file name , line number.

a moniker such t_string explains symbol parser/tokenizer couldn't process finally. isn't cause of syntax mistake however.

it's important previous code lines well. syntax errors mishaps happened earlier. error line number parser conclusively gave process all.

solving syntax errors

there many approaches narrow down , fix syntax hiccups.

  • open mentioned source file. @ mentioned code line.

    • for runaway strings , misplaced operators find culprit.

    • read line left right , imagine each symbol does.

  • more regularily need @ preceding lines well.

    • in particular missing ; semicolons missing @ previous line end / statement. (at least stylistic viewpoint. )

    • if { code blocks } incorrectly closed or nested, may need investigate further source code. use proper code indendation simplify that.

  • look @ syntax colorization !

    • strings , variables , constants should have different colors.

    • operators +-*/. should be tinted distinct well. else might in wrong context.

    • if see string colorization extend far or short, have found unescaped or missing closing " or ' string marker.

    • having 2 same-colored punctuation characters next each other can mean trouble. operators lone, if it's not ++ or -- or parentheses following operator. 2 strings/identifiers directly following each other incorrect in contexts.

  • whitespace friend.
    follow any coding style.

  • break long lines temporarily.

    • you can freely add newlines between operators or constants , strings. parser concretise line number parsing errors. instead of looking @ lengthy code, can isolate missing or misplaced syntax symbol.

    • split complex if statements distinct or nested if conditions.

    • instead of lengthy math formulas or logic chains, use temporary variables simplify code. (more readable = less errors.)

    • add newlines between:

      1. code can identify correct,
      2. the parts you're unsure about,
      3. and lines parser complains about.

      partitioning long code blocks really helps locating origin of syntax errors.

  • comment out offending code.

    • if can't isolate problem source, start comment out (and temporarily remove) blocks of code.

    • as got rid of parsing error, have found problem source. more closely there.

    • sometimes want temporarily remove complete function/method blocks. (in case of unmatched curly braces , wrongly indented code.)

    • when can't resolve syntax issue, try rewrite commented out sections from scratch.

  • as newcomer avoid of confusing syntax constructs.

    • the ternary ? : condition operator can compact code , useful indeed. doesn't aid readability in cases. prefer plain if statements while unversed.

    • phps alternative syntax (if:/elseif:/endif;) common templates, arguably less easy follow normal { code } blocks.

  • the prevalent newcomer mistakes are:

    • missing semicolons ; terminating statements / lines.

    • mismatched string quotes " or ' , unescaped quotes within.

    • forgotten operators, in particular string . concatenation.

    • unbalanced ( parentheses ). count them in reported line. there equal number of them?

  • don't forget solving 1 syntax problem can uncover next.

    • if make 1 issue go away, crops in code below, you're on right path.

    • if after editing new syntax error crops in same line, attempted change possibly failure. (not though.)

  • restore backup of working code, if can't fix it.

    • adopt source code versioning system. can view diff of broken , last working version. might enlightening syntax problem is.
  • invisible stray unicode characters: in cases need use hexeditor or different editor/viewer on source. problems cannot found looking @ code.

  • take care of type of linebreaks saved in files.

    • php honors \n newlines, not \r carriage returns.

    • which issue macos users (even on os x misconfigured editors).

    • it surfaces issue when single-line // or # comments used. multiline /*...*/ comments seldomly disturb parser when linebreaks ignored.

  • if syntax error not transmit on web:
    happens have syntax error on machine. posting same file online not exhibit anymore. can mean 1 of 2 things:

    • you looking @ wrong file!

    • or code contained invisible stray unicode. (see above)
      can find out: copy code web form text editor.

  • check php version. not syntax constructs available on every server.

  • don't use phps reserved keywords identifiers functions / methods, classes or constants.

  • trial-and-error last resort.

if else fails, can google error message. syntax symbols aren't easy search (stack overflow indexed symbolhound though). therefore may take looking through few more pages before find relevant.

further guides:

white screen of death

if website blank, typically syntax error cause.
enable display with:

  • error_reporting = e_all
  • display_errors = 1

in php.ini generally, or via .htaccess mod_php, or .user.ini fastcgi setups.

enabling within broken script late, because php can't interpret/run first line. quick workaround crafting wrapper script, test.php:

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

then invoke failing code accessing wrapper script.

it helps enable phps error_log , webservers error.log when script crashes http 500 responses.


Comments

Popular posts from this blog

sequelize.js - Sequelize group by with association includes id -

android - Robolectric "INTERNET permission is required" -

java - Android raising EPERM (Operation not permitted) when attempting to send UDP packet after network connection -