Unexpected T_Variable parse error in PHP

I have this PHP code and getting this error:

Parse error: syntax error, unexpected '$e' (T_VARIABLE)

In this line:

$error = echo 'Captured: ',  $e->getMessage(), "\n";

I got this information from here. I just wanted to save the echo to a variable. What am I doing wrong here?

Upvotes: 1

Views: 213

Answers (1)

Hanky Panky
Hanky Panky

Reputation: 46900

Comma is not a concatenation operator in PHP, Period is. Secondly, echo doesn't return the string back, it only outputs it. Remove the echo and save your string in your variable like this:

$error = 'Captured: '.  $e->getMessage(). "\n";

Now you may wonder that if this is the case then why do you have an example on PHP.net having comma there?

echo 'Captured: ',  $e->getMessage(), "\n";

It is because that is not string concatenation, those are 3 different parameters being sent to the echo command so in that case it is valid syntax, but for string concatenation it wont be.

Upvotes: 8

Related Questions