Error 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.
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
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.
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.
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.
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.
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.
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.
Else does not expect conditions
⇓
else ($var >= 0)
Solution: Remove the conditions from else.