Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

{ } mark in echo "{$e->getMessage()}"

Tags:

php

I read about this Article I wondering about this part:

try {
    //First try getting our user numero uno
    $user = new User(1);

    //Then, let's try to get the exception
    $user2 = new User('not numeric');
} catch( Exception $e ) {
    echo "Donkey Kong has caught an exception: {$e->getMessage()}";
}

why {$e->getMessage()} must be covered in bracket?
Is there any link explanation on php manual about this?

i know if we don't put bracket it will show error, but want i want is to get the explanation why bracket is needed.

Notice: Undefined property: Exception::$getMessage

like image 458
GusDeCooL Avatar asked Dec 29 '11 18:12

GusDeCooL


2 Answers

It has to do with the fact that this is a complex expression. If you don't include the bracket, i.e.:

echo "Donkey Kong has caught an exception: $e->getMessage()";

...then how does PHP know what variable you're trying to output? You could be trying to do any of the following:

  • output the value of $e, followed by the string "->getMessage()"
  • output the value of $e->getMessage, followed by the string "()"
  • output the value of $e->getMessage()

Placing the brackets around the full expression tells PHP the full expression that needs to be evaluated and included in the string.

like image 192
Matt Huggins Avatar answered Sep 29 '22 23:09

Matt Huggins


You can avoid using curly braces by moving your statement out of the quotes:

echo 'Donkey Kong has caught an exception: ' . $e->getMessage();

But to answer your original question: curly braces are needed to group variable names together, so that PHP understands what you're trying to echo out. Without curly braces, PHP treats the statement as if you're printing out the property $e->getMessage, and a literal string '()', which is not what you intended, of course.

See the Stack Overflow question PHP curly brace syntax for member variable, for more information.

I personally recommend simply concatenating strings using the syntax I provided above.

like image 32
kevinji Avatar answered Sep 30 '22 00:09

kevinji