1D object in string works, 2D object doesn't - puzzled
Hi, everyone!
I have come across a "feature" in PHP5 that is not a great problem to me, but has me puzzled. Can anyone shine some light on this?
The following snippet works fine:
$x->y = "hello";
echo "Let me say $x->y to you!\n";
However, if I modify $x->y (what I shall loosely call a one-dimensional object, analogous to arrays) to $x->y->z (a "two-dimensional object" for lack of a better term) as follows:
$x->y->z = "hello";
echo "Let me say $x->y->z to you!\n";
...this snippet generates the following error message:
Catchable fatal error: Object of class stdClass could not be converted to string
When I change it to:
$x->y->z = "hello";
echo "Let me say " . $x->y->z . " to you!\n";
... then all is well again. So that's the work-around, problem solved, fine... but what has me puzzled as to why this behavior occurs in the first place.
I think it's a question of how the parser identifies variables to be interpolated within a double-quoted string, as "complex" variable notation works, making it clear to the parser where the variable begins/ends within the string:
PHP Code:
$x->y->z = "hello"; echo "Let me say {$x->y->z} to you!\n";
"Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
~ Terry Pratchett in Nation
Yep, that works! And it's easier than concatenating strings with dots. :-)
There are obviously limitations to the parser's ability to recognize variables embedded in strings... but if these are well documented I haven't been able to find out much about it. Oh well. Onward! :-)
Bookmarks