Php __使用字符串时,toString()不得引发异常错误

Php __使用字符串时,toString()不得引发异常错误,php,laravel,Php,Laravel,我正在使用Laravel4进行一个项目。我需要从帖子中检索第一条评论。我使用以下代码来实现这一点 $comments = Comment::where('post_id', $post->id)->first(); 这成功地检索到了第一条注释(我知道这是因为Iprint\r-ed$comments并返回了所有正确的信息) 但是,以下代码行会触发错误\uuu toString()不能引发异常 <td>{{$comments->content}}</td>

我正在使用Laravel4进行一个项目。我需要从帖子中检索第一条评论。我使用以下代码来实现这一点

$comments = Comment::where('post_id', $post->id)->first();
这成功地检索到了第一条注释(我知道这是因为I
print\r
-ed
$comments
并返回了所有正确的信息)

但是,以下代码行会触发错误
\uuu toString()不能引发异常

<td>{{$comments->content}}</td>
{{$comments->content}

当I
print\r
-ed时,它返回类型string,并返回正确的字符串。既然已经是字符串了,为什么它还要尝试将
$comments->content
转换成字符串呢?

根据您提供的信息和我对Laravel的经验,我敢打赌导致异常的代码行是而不是您在问题中提出的代码行

<td>{{$comments->content}}</td>
这为我提供了一个更准确、信息更丰富的例外。有关例外情况的更多信息,请查看


这就是我最初的想法。我知道这不是一个完美的答案,所以请让我知道这是否有效,如果不是这样,我会更新我的答案。祝你好运。

我知道这是一个老生常谈的问题,但对于未来的谷歌用户(像我一样)来说,有另一种方法可以解决这个错误,它独立于您的框架:

public function __toString() 
{
    try {
       return (string) $this->attributeToReturn; // If it is possible, return a string value from object.
    } catch (Exception $e) {
       return get_class($this).'@'.spl_object_hash($this); // If it is not possible, return a preset string to identify instance of object, e.g.
    }
}

您可以在没有框架的自定义类中使用它,也可以在Symfony2/doctor中的实体中使用它。。。它也可以工作。

它说
视图的
方法的
不能抛出异常。可能,您的视图中出现了一些错误。这是您的问题:
Symfony\Component\Debug\Exception\FatalErrorException Method\View\View::\uuu toString()不能引发异常。
是完整的错误@neoascetic。还有,那会是什么样的错误?@735Tesla没有告诉我我在做什么wrong@InsertNameHere未定义的变量。未闭合的卷曲支架。任何类型的错误,事实上这是一个伟大的提示!我能够通过使用var_dump($somevar)剥离异常链,直到找到问题的根源(这是一个未初始化的关系)。
public function __toString() 
{
    try {
       return (string) $this->attributeToReturn; // If it is possible, return a string value from object.
    } catch (Exception $e) {
       return get_class($this).'@'.spl_object_hash($this); // If it is not possible, return a preset string to identify instance of object, e.g.
    }
}