繁体   English   中英

php echo可捕获的致命错误:类的对象……无法转换为

[英]php echo Catchable fatal error: Object of class … could not be converted to string in

我在尝试显示某些变量时收到错误,如下所示:

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 "..." 还有一些奇怪的行为:在简单的var上回显,有效; 在对象的简单属性上回显作品; 在另一个对象内部的对象的简单属性上回显不起作用。

这是echo "id is {$url->model->id}";echo "id is {$url->model->id}"; 正确的方式? 有没有更简单的方法?

"{$var}"是通用字符串变量插值语法。 对于一维数组,有些语法快捷方式称为简单语法

echo "$arr[foo]";

但是,这不适用于多维数组,例如"$arr[foo][bar]" 这只是硬编码的特殊情况。 对于对象也是如此。 "$obj->foo"是一种硬编码的特殊情况,可以使用,而更复杂的情况将必须由复杂的"{$obj->foo->bar}"语法处理

更新:

也许我是错的,仅回显$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}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM