在_-toString方法中使用Laravel JSON响应

在_-toString方法中使用Laravel JSON响应,laravel,symfony,Laravel,Symfony,我的类中有一个返回JSON响应的方法 public function response(){ return \Response::json(['data'=>'somedata']); } 为了能够使用更多的chain方法,每当我想返回一个对象作为响应时,我都想使用_toString()方法。像这样: public function __toString(){ return $this->response(); } 但我得到了这个错误: Method MyC

我的类中有一个返回JSON响应的方法

public function response(){

    return \Response::json(['data'=>'somedata']);
}
为了能够使用更多的chain方法,每当我想返回一个对象作为响应时,我都想使用_toString()方法。像这样:

public function __toString(){

    return $this->response();

}
但我得到了这个错误:

Method MyClass::__toString() must return a string value

这是有道理的,但我该怎么做呢。我查看了Laravel和Symfony
JsonResponse
类,但找不到解决此问题的方法。我尝试了
getContent()
,但这只是一个字符串,不是正确的Json响应

经过大量研究,我找到了解决办法。我不知道这是不是最好的,但这是:

public function __toString(){

    $this->response()->send();
    return '';
}

这实际上是对
Symfony\Component\HttpFoundation\Response::send()
方法的调用,而不是返回字符串。

这是一个延迟响应,但我找到了一个更好的解决方案,让Laravel处理响应:

public function __toString(){
    return Response::json($this)->content() ' Returns a string
}