2017-02-09 13 views
0

我的方法在我的類中返回一個JSON響應。在__toString方法中使用Laravel JSON響應

public function response(){ 

    return \Response::json(['data'=>'somedata']); 
} 

爲了能夠使用更多的鏈方法,我希望使用__toString()方法,每當我想返回一個對象作爲響應。就像這樣:

public function __toString(){ 

    return $this->response(); 

} 

但我得到這個錯誤:

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

這是有道理的,但我怎麼能做到這一點。我看着Laravel和Symfony JsonResponse類,找不到解決這個問題的方法。我試過getContent(),但那只是一個字符串,不是一個合適的Json響應。

回答

0

經過大量的嘗試和研究,我發現了一個解決方案。我不知道這是否是最好的,但在這裏它是:

public function __toString(){ 

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

這實際上是對Symfony\Component\HttpFoundation\Response::send()方法,而不是返回一個字符串的呼叫。