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?
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.
Just move the $ sign my friend.
<?php
$obj = new stdClass;
$obj->foo = 123;
echo "foo: {$obj->foo}";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With