how to convert object into string in php [duplicate] - php

This question already has answers here:
Closed 10 years ago.
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

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";}

Use the casting operator (string)$yourObject;

You have the print_r function, check docs.

There is an object serialization module, with the serialize function you can serialize any object.

In your case, you should simply use
$firstapiOutput->document_number
as the input for the second api.

Related

how to solve Object of class stdClass could not be converted to string PHP

I am using php and decode json format to array as following code
$sub_cats_ids=array();
$sub_cats_ids=json_decode($_POST['sub_cats']);
I want to echo first item in array to test if it works fine as following code
echo current($sub_cats_ids);
but I get this error message
Object of class stdClass could not be converted to string
I tried this code also
echo $sub_cats_ids[0];
but I get the same error message
how I can solve this issue
The error message is crystal clear, isn't it? The current element in the array is an object, not a string. You cannot "echo" an object, but only a string. So php tries to convert the object into a string but fails, since no such conversion is defined for an object of the generic standard class.
You need to use a function to output an object instead of the echo command, or you need to to convert that object into a string which you can output:
<?php
//...
var_export(current($sub_cats_ids));
Or to echo the object:
<?php
//...
echo var_export(current($sub_cats_ids), true);
UPDATE:
Your comment below suggests that unlike what you wrote in the question you do not want to output the object itself, but only a specific property of that object. That means you need to access that property in the object, php cannot somehow magically guess that you want to do that.
Without you posting additional information all I can do here is guess what you actually need to do:
<?php
//...
$object = current($sub_cats_ids);
echo $object->IT;

How to get rid of array/object casting in PHP?

Some methods/functions only accept/return arrays, others only get/give objects. In my day to day PHP programming I have to repetitively convert objects to array and vice versa. ((object) ['x'=>3] and (array) (new stdClsss())).
Most classes do not implement ArrayAccess. Smartly in JavaScript, these two syntaxes are interchangeable. Is there any hack, workaround to stick to one of them and get rid of variable casting and "Cannot use object of type xxx as array in " or "Cannot use object of type stdClass as arhray in "Cannot access property on non-object" messages.
I came up with ary.
$var= ary(['x' => 'foo', 'y' => 'bar']);
$foo = $var->x; //or
$foo = $var['x'];
Try using php serializing function, instead of trying to convert them.
$array = array();
$obj = serialize($array);
$again = unserialize($obj);
This will help you if your interchange is about to save datum.
if, working with the object is your bulk task, try to define a class library for your object and then, implement your function like ToArray(), ToString(), ToObject() or ToStorable(), instead of converting them in your code with natural functions.

Can I change the variable type from object to string? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
how to convert object into string in php
I have a variable that contain some object (SimpleXML).
Can I change the type of this variable, and to assing it to this variable itself?
Like this:
$test = (string)$test;
var_dump($test);
The above code does not work, so the output is still object(SimpleXMLElement) and not a string.
But when I assign it another variable, like $new_test = (string)$test it works well, and the var_dump output is string]
If you want the string content, use asXML method.
var_dump($test->asXML());
It depends on how SimpleXML implements the magic function __toString(). Its different from class to class. But if its not implemented, PHP will throw a fatal error.
So, typecasting directly from object to string does not work unless the __toString() method is implemented.
You can't convert an object to string just like adding a declaration, it might work but it wont behave like desired there's a greate article though written before here in stack on how you should do it the optimal way which is by adding a tostring method read more here...
how to convert object into string in php
It depends on the object being converted. For SimpleXML you probably want its asXML method: http://www.php.net/manual/en/simplexmlelement.asxml.php. For general objects, you can typecast to string if the objects implements the __toString() method. Another option would be var_export(...,true), but that is rarely useful except for debugging.
Typecast the SimpleXMLObject to a string
$foo = array( (string) $xml->parent->child );
<?php
$xmlstring = "<parent><child> hello world </child></parent>";
$xml = simplexml_load_string($xmlstring);
$foo = array( (string) $xml->child );
var_dump($xml).PHP_EOL;
var_dump($foo);
?>
Output
object(SimpleXMLElement)#1 (1) {
["child"]=>
string(13) " hello world "
}
array(1) {
[0]=>
string(13) " hello world "
}
http://codepad.org/Bss1rndd

PHP parsing from print_r()

I'm working with some API integration and I have a limitation with understanding Objects.
Not my code, but here's what I have:
<?php
print_r(pingSample());
?>
The result on the browser is this:
PingResponse Object ( [PingResult] => 1 )
The function pingSample is not mine, it's from Docusign.
I want to just extract the "1", or if it's a bad result I'm sure it will return "0".
I'm not experienced with Object Oriented coding, yet. So, I'm assuming this is a simple example, in an API setting. But I'm not sure.
For those who want to laugh at my attempt:
$blah = pingSample();
echo $blah['PingResult'];
So far, nothing returns on the browser. Apache logs return this:
PHP Fatal error: Cannot use object of type PingResponse as array
How do I extract only the value of PingResult?
Object properties are accessed by using the pointer (arrow) notation, not array (bracket) notation.
$blah = pingSample();
echo $blah->PingResult;
Read more on Classes and Objects in PHP.
$blah = pingSample();
echo $blah->PingResult;
Try this :
echo $blah->PingResult;

How to save simplexml node value to string?

I am trying to get a value in a node, and save it into a string variable. I haven't used PHP in about 5 years so I have no idea what is going on?
string $errorMessage = (string)$error->message);
print_r($errorMessage);
returns nothing
first do
$errorMessage = (string)$error->message;
and dont do print_r its used for echoing array simply use echo instead so
echo $errorMessage;
Php is not strongly typed language so you dont need to do string $errorMessage; , but still casting is pressent in php , coz objects such as simplexml implements __toString magic function which gets called automaticaly when you cast that object as string .

Categories