Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't you access "deeper" object variables when said object variable is used in a string?

Tags:

php

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.

like image 527
Fake Code Monkey Rashid Avatar asked Nov 28 '22 10:11

Fake Code Monkey Rashid


2 Answers

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.

like image 94
DVK Avatar answered Dec 01 '22 01:12

DVK


$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.

like image 42
webbiedave Avatar answered Dec 01 '22 00:12

webbiedave