__toString()使用字符串时不得抛出异常错误 [英] __toString() must not throw an exception error when using string

查看:414
本文介绍了__toString()使用字符串时不得抛出异常错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将Laravel 4用于我正在从事的项目.我需要从帖子中检索第一条评论.我使用下面的代码来做到这一点.

I am using Laravel 4 for a project I am working on. I need to retrieve the first comment from the post. I use the following code to do so.

$comments = Comment::where('post_id', $post->id)->first();

这成功检索了第一个注释(我知道这是因为我print_r -ed $comments并且返回了所有正确的信息).

This successfully retrieves the first comment (I know that because I print_r-ed $comments and it returned all the right information).

但是,下面的代码行触发错误__toString() must not throw an exception

However, the following line of code triggers the error __toString() must not throw an exception

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

当我print_r -ed时,它返回类型字符串,并且还返回正确的字符串.为什么那么当它已经是字符串时,它甚至会尝试将$comments->content转换为字符串类型?

When I print_r-ed that it returned type string, and returned the correct string as well. Why then would it even try to convert $comments->content to type string when it is already a string?

推荐答案

根据您所提供的信息以及我对Laravel的经验,我敢打赌导致异常的代码行不是不是您在问题中添加的行.

Based off the information you've given and my experience with Laravel I'd bet that the line of code causing the exception is not the line you've put in your question.

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

此异常抱怨视图抛出异常.如果这行是问题所在,那么您将获得关于$ comments-> content如何无法转换为字符串的更具描述性的异常.您还已经测试过它确实是字符串.

This exception is complaining about the view throwing an exception. If this particular line was the issue you'd get a more descriptive exception about how $comments->content can't be converted into a string. You've also already tested that it is indeed a string.

我建议找到要在视图中回显视图"对象的位置,并像这样进行更改.

I'd recommend finding where your "View" object is being echoed to the view and change it like so.

{{ View::make('yourbladefile')->__tostring() }}

这为我提供了更准确,更有用的例外.有关您的异常的更多信息,您应该查看为什么无法引发异常来自__toString()吗?

This worked for me by providing a more accurate and informative exception. For more info on your exception you should check out Why it's impossible to throw exception from __toString()?

这就是让我想到这个主意的原因.我知道这不是一个完美的答案,所以请告诉我这是否可行,如果事实并非如此,我将更新我的答案.祝你好运.

It's what gave me the idea in the first place. I know it's not a perfect answer so please let me know if this works and I'll update my answer if this turns out not be the case. Good luck.

这篇关于__toString()使用字符串时不得抛出异常错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆