Catchable fatal error: Object of class stdClass could not be converted to string in

Asked

Viewed 4,958 times

1

I made a request and the result brought $result. But I wanted to access inside the string as object and this error appears. I saw similar mistakes in other questions, but it wasn’t clear to me.

echo $result;
echo "<br>";
echo var_dump($result);
echo "<br>";
echo json_decode($result);
{"response":{"dsLOGIN":{"dsLOGIN":{}}}}
string(39) "{"response":{"dsLOGIN":{"dsLOGIN":{}}}}" 

Error:

Catchable fatal error: Object of class stdClass could not be converted to string in

  • What happens if you make one print_r($result);?

  • {"response":{"dsLOGIN":{"dsLOGIN":{}}}} - The same line as echo $result @Thiagosantos

  • In which line are you making the mistake? In this: echo json_decode($result);?

  • Yeah, right on it. echo json_decode($result); @Thiagosantos

  • json_decode($result); returns a PHP Object, and with an ECHO you try to write that Object as String, which is causing this error.

1 answer

2


OBJECT OF CLASS STDCLASS

When using json_decode() you have as a result an Object, or an Array of Objects (Source) and, when using ECHO in an Object, it causes an attempt to convert it to String, causing Error:

Catchable fatal error: Object of class stdClass could not be converted to string in

To write an object directly you need to use print_r() thus displaying even its properties (Source).

In your case the following must work appropriately:

echo $result;
echo "<br>";
echo var_dump($result);
echo "<br>";
$jsonResult = json_decode($result);
print_r($jsonResult); // $jsonResult já é um Objeto
print_r($jsonResult->response) // $jsonResult->esponse também contém um Objeto
  • Now, I get it. I was just using the echo and was confusing me. Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.