Syntax error, unexpected T (something)

From Php

Revision as of 05:29, 11 November 2008 by DuckySherwood (Talk | contribs)
(diff) ← Older revision | Current revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Messages like syntax error, unexpected T_IF, syntax error, unexpected T_STATIC, and so on are admittedly quite cryptic. It means that the PHP interpreter found an a reserved word someplace that it didn't expect it. (Which word? whatever comes after the underscore. So if the message is syntax error, unexpected T_IF, look for an if.)

Frequently, this means that the previous program element (assignment statement, if statement, echo, whatever) wasn't finished/closed correctly.

Contents

Missing semicolon

WRONG

 $foo = $bar  // note no semicolon!
 if($bar == $baz)
 {
   // do something...
 }

RIGHT

 $foo = $bar;
 if($bar == $baz)
 {
   // do something...
 }

Missing curly braces

You can get an error about an unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING if you are missing curly braces around an associative array element inside a quoted string.

WRONG

 echo "$foo['bar'], hello";

WILL WORK

 echo $foo['bar'];
 echo ", hello";

BEST

 echo "{$foo['bar']}, hello";

Reserved word

It could also mean that you're using a reserved word someplace you shouldn't.

WRONG

 if(static == 4) // static is a reserved word
 {
   // do something
 }

WORKS, BUT IS A BAD IDEA

 if($static == 4)  // you might forget the $ and mess yourself up
 {
   // do something
 }

RIGHT

 if($signalQuality == 4)  // you might forget the $ and mess yourself up
 {
   // do something
 }

Missing assignment

You can get an unexpected T_STRING or unexpected T_LNUMBER error if you leave out an equals sign in an assignment statement, e.g.

WRONG

 $foo "moo"; // missing =, unexpected T_STRING
 $bar 7;     // also missing =, unexpected T_LNUMBER

RIGHT

  $foo = "moo";
  $bar = 7;