__toString() must not throw an exception error when using string

匿名 (未验证) 提交于 2019-12-03 00:50:01

问题:

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(); 

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

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

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

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?

回答1:

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> 

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() }} 

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.



回答2:

I know that this is an old question, but for future googlers (like me) there is another way to solve that error, and it is independent of your framework:

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.     } } 

You can use it with your custom class with no framework, or with an entity in Symfony2/Doctrine... It will work as well.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!