我在尝试显示一些变量时收到错误,如下所示:
echo "id is $url->model->id";
问题似乎是 echo 只喜欢以这种方式显示的简单变量(如 $id 或 $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;
}
}
然后
$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']}";
我不知道它为什么有效,我只是猜测语法。
在 php 手册中,它没有说明如何将 echo "..."
用于对象。还有一些奇怪的行为:在简单的变量上回显,作品;对对象的简单属性进行回显工作;对位于另一个对象内部的对象的简单属性进行回显不起作用。
这是echo "id is {$url->model->id}";
正确的方式吗?有没有更简单的方法?
更新:
也许我错了,只回显$url->model
或$url->model->id
会尝试将其转换为字符串并返回它,以便您可以这样做,但您必须在模型中具有__toString
函数
做了一个例子来澄清我的观点:
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;
}
public function __toString()
{
return (string) $this->id ;
}
}
$url = new url("1");
echo "id is $url->model->id"; // it will convert $url->model to "1" , so the string will be 1->id
echo "id is $url->model"; // this will work now too
$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
但我不确定对?????有什么echo "this is {$baz['value']}";
查看__toString以获取有关魔术方法的更多信息
但我宁愿坚持{$url->model->id}
.
"{$var}"
是通用字符串变量插值语法。有一些语法快捷方式称为一维数组等内容的简单语法:
echo "$arr[foo]";
但这不适用于多维数组,例如 "$arr[foo][bar]"
.这只是一个硬编码的特例。对象也是如此。 "$obj->foo"
是有效的硬编码特殊情况,而更复杂的情况必须由复杂的"{$obj->foo->bar}"
语法处理。