Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert object into string in php [duplicate]

Tags:

php

Possible Duplicate:
PHP ToString() equivalent

how to convert object into string in php

Actually i am dealing with web service APIs.i want to use output of one API as a input for another API. when i am trying to do this i got error like this:Catchable fatal error: Object of class std could not be converted to string in C:\ ...

this is the output of first API::stdClass Object ( [document_number] => 10ba60 ) now i want only that number to use as input for 2nd AP

print_r and _string() both are not working in my case

like image 565
JJ. Avatar asked Mar 18 '10 11:03

JJ.


People also ask

How to convert PHP object to string?

_toString() function in PHP is extensively used to convert the object related to it into string whereas the serialize() function is used to convert the object and return a string containing entire byte-stream which at later point of time is used for representation of any value that is stored in the PHP variable being ...

What is Tostring PHP?

Definition and Usage. The __toString() function returns the string content of an element. This function returns the string content that is directly in the element - not the string content that is inside this element's children!


2 Answers

You can tailor how your object is represented as a string by implementing a __toString() method in your class, so that when your object is type cast as a string (explicit type cast $str = (string) $myObject;, or automatic echo $myObject) you can control what is included and the string format.

If you only want to display your object's data, the method above would work. If you want to store your object in a session or database, you need to serialize it, so PHP knows how to reconstruct your instance.

Some code to demonstrate the difference:

class MyObject {    protected $name = 'JJ';    public function __toString() {     return "My name is: {$this->name}\n";   }  }  $obj = new MyObject;  echo $obj; echo serialize($obj); 

Output:

My name is: JJ

O:8:"MyObject":1:{s:7:"*name";s:2:"JJ";}

like image 56
Greg K Avatar answered Oct 22 '22 05:10

Greg K


Use the casting operator (string)$yourObject;

like image 21
Webleeuw Avatar answered Oct 22 '22 06:10

Webleeuw