Laravel 错误:方法 Illuminate\View\View::__toString() 不得抛出异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28329304/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 10:49:59  来源:igfitidea点击:

Laravel Error : Method Illuminate\View\View::__toString() must not throw an exception

phplaravel

提问by user3150060

I am using larval 4.2 and I am getting the following error in my wrapper.php my view file :

我正在使用 larval 4.2 并且在我的 wrapper.php 我的视图文件中收到以下错误:

   <?php echo View::make('layouts/blocks/header')->with('sidebar', $sidebar)->with('active', $active); ?>
   <?php echo $content; ?>
   <?php echo View::make('layouts/blocks/footer'); ?>

Error:

错误:

   Error : Method Illuminate\View\View::__toString() must not throw an exception

Do you know whats causing this?

你知道是什么原因造成的吗?

回答by Alan Storm

Laravel renders its views by casting an Illuminate\View\Viewobject as a string. If an object is cast as a string and has a __toStringmethod set, PHP will call the __toStringmethod and use that value from that as the cast value.

Laravel 通过将Illuminate\View\View对象转换为字符串来呈现其视图。如果对象被转换为字符串并__toString设置了方法,PHP 将调用该__toString方法并将该方法中的值用作转换值。

For example, this program

例如,这个程序

class Foo
{
    public function __toString()
    {
        return 'I am a foo object';
    }
}
$o = new Foo;
echo (string) $o;

will output

会输出

I am a foo object.

There's a big caveat to this behavior -- due to a PHP implmentation detail, you can't throw an exception in __toString.

这种行为有一个很大的警告——由于 PHP 实现细节,您不能在__toString.

So, it looks like the problem you're having is something in your view doesthrow an exception. Based on the information you've provided, the error could be anything. The way I'd debug this further is to try running the PHP code in your view

因此,看起来您遇到的问题是您认为确实引发了异常。根据您提供的信息,错误可能是任何内容。我进一步调试的方法是尝试在您的视图中运行 PHP 代码

echo View::make('layouts/blocks/header')->with('sidebar', $sidebar)->with('active', $active);
echo $content;
echo View::make('layouts/blocks/footer');

outside of a view (a route, a controller action, etc), making sure $sidebar, $content, etc have the same values. This should still throw an exception, but because it's outside of __toStringPHP will give you more information on whyit threw an exception. With a real error message you'll be able to address the actual problem.

的图(路线,控制器动作等)的外面,并确认$sidebar$content等具有相同的值。这应该仍然会抛出异常,但因为它在__toStringPHP之外会为您提供更多关于它为什么会抛出异常的信息。通过真实的错误消息,您将能够解决实际问题。