I received the error while trying to display some variable like so:
echo "id is $url->model->id";
The problem seems to be that echo only likes simple variables to be displayed in this way (like $id or $obj->id).
class url {
public function __construct($url_path) {
$this->model = new url_model($url_path);
}
}
class url_model {
public function __construct($url_path) {
$this->id = 1;
}
}
and then
$url = new url();
echo "id is $url->model->id"; // does not work
$t = $url->model->id;
echo "id is $t"; //works
$t = $url->model;
echo "id is $t->id"; //works
echo "id is {$url->model->id}"; //works. This is the same syntax used to display array elements in php manual.
//php manual example for arrays
echo "this is {$baz['value']}";
I don’t know why it works, I just guessed the syntax.
In php manual it doesn’t say how to use echo "..." for objects. Also there is some strange behavior: echo on simple vars, works; echo on simple property of an object works; echo on simple property of an object that is inside another object does not work.
Is this echo "id is {$url->model->id}"; the right way? Is there a simpler way?
"{$var}"is the universal string variable interpolation syntax. There are some syntax shortcuts known as simple syntax for things like one-dimensional arrays:This does not work for multi-dimensional arrays though, e.g.
"$arr[foo][bar]". It’s simply a hardcoded special case. The same is true for objects."$obj->foo"is a hardcoded special case that works, while more complex cases will have to be handled by the complex"{$obj->foo->bar}"syntax.