Recent Posts

Showing posts with label unexpected. Show all posts
Showing posts with label unexpected. Show all posts

How to debug: unexpected T_CONSTANT_ENCAPSED_STRING PHP

The unwieldy name T_CONSTANT_ENCAPSED_STRING denotes actual "string" literals, both in double quotes or 'single' quoted variety.

Incorrect variable interpolation

And it commes up for syntax errors most frequently when utilizings PHPs variable interpolation incorrectly:

                               
echo "Here comes a $wrong['array'] access";
While quoting arrays keys is a must in PHP context, in double quoted strings (or HEREDOCs) this is a mistake. The parser complains about the contained single quoted 'string', because it actually expects a bare word.

More precisely it expected the PHP2/simple syntax within double quotes for array references:

echo "This is only $valid[here] ...";
For nested arrays or deeper object references etc. you need the complex curly string expression syntax explained in the manual:

echo "Use {$array['as_usual']} with curly syntax.";
If unsure, this is commonly safer to use and often considered more readable.

Missing concatenation

If a string follows an expression that was valid thus far, 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 me and you, PHP can't guess that you meant to append this string as well.

Confusing string quote enclosures

Same thing happens if you confuse single ' and double " quotes without escaping:

                
print "<a href="' . $link . '">click here</a>";
That example started with double quotes. But double quotes were also destined for the HTML attributes. The intended concatenation operator within is however part of a second string in single quotes. -- This is a good example where you shouldn't break out of double quotes, but instead just use proper \" escapes for the HTML attributes´ quotes:

print "<a href=\"{$link}\">click here</a>";
While this can also lead to syntax confusion, a nice IDE helps by colorizing the escaped quotes differently.

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.

Array or parameter 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 with syntax highlighting off, but even then. But IDEs usually help.

Same thing for function calls:

                          
myfunc(123, "text", "and"  "more")

How to debug: unexpected T_VARIABLE PHP

An unexpected T_VARIABLE means that there's a $variable where there can't be one yet.

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

Another occurence is in string concatenation, where the concatenation operator . was forgotten:

                               
print "Here comes the value: "  $value;
Can happen for other expressions and operators of course.

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 you want to use variable variables instead.

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.

How to debug: unexpected T_STRING PHP

T_STRING is a bit of a misnomer. It does not denote a "string", but refers to raw identifiers like name, bare words / plain text within the source.

Misquoted strings

Quite typically it occurs within misquoted strings however. If you forgot to correctly escape the content of "strings", have stray"/' quotes in it for example:

                                 
 echo "<a href="http://example.com">click here</a>";
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 if you want to output HTML with double quotes within. Use double quote string encloseres if you want to interpolate variables, and then watch out for escaping. For lengthier output, use multiple echo/print lines instead of trying to escape in and out, or better yet consider a HEREDOC section.

Unclosed strings

If you miss a closing " then a syntax error typically materializes on a later line:

                                                       
echo "Some text", $a_variable, "and some runaway string ;
success("finished");
                   ⇯
It's not just T_STRINGs which the parser may protest then (but it's the most common occurence). For example Unexpected '>' often points out unquoted literal HTML after strings.
Again, you can probably see the helpful syntax highlighting here on Stackoverflow which makes it apparent.

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”;
They're often Unicode characters, thusly interpreted as constants, and therefore the following text handled as bareword/T_STRING.

The missing semicolon again

As always it's sensible to also look into the preceding line. PHP will complain about a word in one line (the parser doesn't know yet if that's a constant or a function call or something else). But the culprit is higher up in the code:

       
func1()
function2();
Short open tags and <?xml headers in php scripts

If short_open_tags are enabled, then you can't begin your PHP scripts with an XML declaration:

      
<?xml version="1.0"?>
PHP will see the <? and reclaim it for itself. It won't know what to do with the stray xml following the open marker however. While that might pass as an undeclared constant, the following version bareword will trigger a parser failure.

It's commonly advised not to mix in XML in PHP scripts, or at least have the courtesy to turn off short_open_tags if that's a common use case.

Invisible unicode characters

A most hideous cause for syntax errors are unicode characters, such as the non-breaking space (commonly &nbsp;). PHP allows Unicode characters as identifier names. If you get this parser error for unsuspecting code such as:

<?php
    print 123;
You need to break out your hexeditor. What looks like plain spaces and newlines here, may contain invisble constants. Try to reedit everything, remove whitespace and add normal spaces back in. Or use this evil trick to discover the culprit:

<?php
    ;print 123;
The redundant ; semicolon here will convert the preceding invisible character into an undefined constant reference (expression as statement). Which in return will trigger a notice.

How to solve: Parse error: syntax error, unexpected T_VARIABLE

Possible scenario
I can't seem to find where my code has went wrong. Here is my full error:
Parse error: syntax error, unexpected T_VARIABLE on line x
what i am trying
$sql = 'SELECT * FROM dealer WHERE id="'$id.'"';
Answer
Parse error: A problem with the syntax of your program, such as leaving a semicolon off of the end of a statement or in like in above case missing . operator . The interpreter stops running your program when it encounters a parse error.
In simple word this is a syntax error, meaning that there is something in your code stopping it from being parsed correctly and therefore run.
What you should do is check carefully at the lines around where the error is for any simple mistakes
That error message means that in line x of the file, the PHP interpreter was expecting to see an open parenthesis but instead, it encountered something called T_VARIABLE. That T_VARIABLE thing is called a token. It's the PHP interpreter's way of expressing different fundamental parts of programs. When the interpreter reads in a program, it translates what you've written into a list of tokens. Wherever you put a variable in your program, there is aT_VARIABLE token in the interpreter's list.
so make sure you enable at least E_PARSE in your php.ini. Parse errors should not exist in production scripts.
i always recommended to while coding
error_reporting(E_ALL);
Also a good idea to use IDE which will let you know parse error while typing. You can sue
  1. NetBeans (fine peace of beauty, free)(imho its best)
  2. PhpStorm (Uncle Gordon love this :P , paid)
  3. Eclipse (beauty and the beast free)