Why can't you access "deeper" object variables when said object variable is used in a string?
What I mean is, while you can do something like this:
$foo = "Yo dawg I herd you like $bar->baz";
This:
$foo = "Yo dawg I herd you like $bar->baz->qux";
Results in the following error:
"Object of class * could not开发者_如何转开发 be converted to string"
The cleanest way around it seems to be something like:
$baz = $bar->baz;
$foo = "Yo dawg I herd you like $baz->qux";
So why doesn't it work and is there is a better solution?
NOTICE:
I know some people prefer to have their variables outside of their strings but this is not the venue to talk about such preferences and does not address the question I'm asking so I'd appreciate if you leave such subjective sentiments out of this. Thank you.
Because a simple interpolation (see description in http://php.net/manual/en/language.types.string.php - "Variable parsing" section) explicitly was designed to only interpolate embedded "variable, an array value, or an object property in a string".
Please note that it's designed to interpolate "an object property", NOT an "arbitrary expression". To do the latter, your parser would need to do a MUCH MUCH harder jobs when parsing strings.
For the arbitrary expression, you need to use complex (curly) syntax introduced in PHP4 by enclosing said expression in curly braces: {$bar->baz->qux}
within the string.
$foo = "Yo dawg I herd you like {$bar->baz->qux}";
http://www.php.net/manual/en/language.types.string.php#language.types.string.parsing
The only why I can give you is that the designers chose to implement it this way. For instance, you can't include a function return value in the braces. This is just a design choice.
精彩评论