3

I want to echo the value of a property using magic quotes.

$obj = new stdClass;
$obj->foo = 123;
echo "foo: ${obj->foo}";

This fails with the following error message:

Parse error: syntax error, unexpected T_OBJECT_OPERATOR in /foobar/test.php on line 3

I know I could write something like this:

echo "foo: ".$obj->foo;

But shouldn't the curly brackets work in this case too?

Eva Baentsch
  • 113
  • 1
  • 7

2 Answers2

4

Yours is almost right:

echo "foo: {$obj->foo}";

The php reference for complex string syntax says:

Any scalar variable, array element or object property with a string representation can be included via this syntax. Simply write the expression the same way as it would appear outside the string, and then wrap it in { and }. Since { can not be escaped, this syntax will only be recognised when the $ immediately follows the {.


I should have also mentioned this at the time I answered, but the brackets aren't actually needed for this expression.

echo "foo: $obj->foo";

should work just fine.

Don't Panic
  • 41,125
  • 10
  • 61
  • 80
1

Just move the $ sign my friend.

<?php
    $obj = new stdClass;
    $obj->foo = 123;
    echo "foo: {$obj->foo}";
Alex
  • 478
  • 2
  • 11