Recent Posts

Showing posts with label T_CONSTANT_ENCAPSED_STRING. Show all posts
Showing posts with label T_CONSTANT_ENCAPSED_STRING. 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")