PHP parsing from print_r() - php

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;

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.

AS3, PHP & JSON - Decoding one object is fine, an array returns null

I've been hunting around for a few hours and I still have no idea what's going on. I'm new to PHP, but fairly comfortable with simple Flash stuff.
I'm passing a JSON object from PHP into Flash AS3 using URLLoaders, etc. This is my PHP-created test JSON array:
$objJSON = array('sample' => null);
$objJSON['sample'] = "TESTING";
$objJSON['sample2'] = "TESTING2";
$objJSON = json_encode($objJSON);
I return it to flash with
echo "arrayData=$jsonArray";
When I parse that as a SINGLE object in flash, using
var tempJSON = JSON.decode(event.target.data.arrayData);
I get 'TESTING' as my output (textBox.text = tempJSON.sample; using localhost via WAMP), which is correct. Everything looks good, there's communication, the JSON library is being used right, the object is there and accessible...
BUT! When I treat it as an Array (because that's what it is) by changing the code directly above (and touching NOTHING else) to:
var tempJSON:Array = JSON.decode(event.target.data.arrayData, true);
I throw a compiler error of:
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at com.adobe.serialization.json::JSONTokenizer/nextChar()[....\json\JSONTokenizer.as:545]
Running the swf in localhost gets me no return where I used to get string. Am I making some newbie mistake that the data suddenly becomes null when I treat it like an array?
I've checked the validity of my JSON via the output in PHP and it checks out. I've made sure I have no extra echos in the PHP class being called. I'm just stumped.
FIX'D!
Guided by the comments, I basically wasn't forming my JSON to be an array, just objects with multiple properties. The correct way to do it was:
$objArray = array(
array(
"sample1" => "Testing!",
"sample2" => "Testing2!",
),
array (
"sample1" => "Testing!",
"sample2" => "Testing2!",
)
);
$objArray = json_encode($objArray);
I believe it is because your JSON is decoding into an object and not an array. This will happen if you are using non-integer values as your array keys (ie. 'sample', 'sample2').
I'm not overly familiar with AS3, but you will likely need to cast it into an Object-like instance instead of an Array.
$objJSON = array('sample' => "TESTING", 'sample2' => "TESTING2");
echo json_encode($objJSON);
// Will output
{ "sample": "TESTING", "sample2": "TESTING2" }
This is not array notation using JSON. It is object notation.
I hope this helps!

Is there a version of the PHP array that is pass-by-reference?

I'm asking this because I'm working with a recursive function that generates a large array tree and the pass-by-copy aspect of the arrays are completely screwing with my head. I've tried using ArrayObject, but that's really an object, isn't it? None of the array_keys type array functions work with it, and json_encode doesn't understand that it's an array.
I'd like a version of the PHP array that feels, smells and looks like the normal array, but is pass-by-reference. Is there anything like that in PHP?
Woah woah hold up people; I'm well aware of the & symbol but that's what I'm trying to avoid. As my question specifies (^) I'm looking for a version of the PHP array that is pass-by-reference by default
I'd like a version of the PHP array that feels, smells and looks like
the normal array, but is pass-by-reference. Is there anything like
that in PHP?
No, There is nothing like that in PHP.
Json encode should be able to pass objects. But if you for some reason NEED an array, you can't use objects and then cast it as array before encoding to json?
<?php
$object = (object)array("number"=>1);
function addToTen($object){
if($object->number<10){
$object->number++;
addToTen($object);
}
}
addToTen($object);
echo json_encode((array)$object);
//echoes {"number":10} with or without casting it as an array
?>
You could also wrap your array in an object of course, like this:
$object = new stdClass;
$object->a = array();
function fillUpArray($object){
if(count($object->a)<10){
$object->a[] = "someValue";
fillUpArray($object);
}
}
fillUpArray($object);
echo json_encode($object->a);
//echoes ["someValue","someValue","someValue","someValue","someValue","someValue","someValue","someValue","someValue","someValue"]
I must admit though I don't entirely get what you're trying to accomplish here :S
Yes, see the PHP manual page: http://php.net/manual/en/language.references.pass.php
Stop using &references altogether, in php they get cumbersome pretty quickly, (being, unlike C pointers, almost transparent, the only way to check you're actually using a reference is by assigning junk to it and check the effect this has on a tree) and you don't seem willing to handle that level of subtlety.
(Nor to wrap it with an ArrayObject, apparently)
Are you aware objects ARE references?
Object-wrap every aspect of your tree and your life will instantly get less miserable.
I am not aware of any such built-in functionality in PHP that you ask. Also, you are quite reluctant to use references. Hmmm...you could send a request to the PHP dev team to include such stuff in PHP v6, along with unicode that is supposed to come, that would us all happy :).
However, can you use a class and assign your initial array to one of the class variables and then process it and get it back after the recursion. Not sure if that would work, but anyway here it is:
<?php
class noReference {
public $myData;
public function __construct( $data ) {
$this->myData = $data; // this is your initial array.
}
// this function works on the myData array and changes it.
public function myRecursiveFunction() {
// your code here
$this->myRecursiveFunction(); // called as per your logic
// your code here
}
public function getData() {
return $this->myData;
}
public function __destruct() {
unset( $this->myData );
}
}
$data = array(/*WHATEVER_PLEASES_YOU*/);
$noref = new noReference( $data );
// this will be your recuresive function
$noref->myRecursiveFunction();
//your data here
$result = $noref->getData();
?>
Let me know if this works. Cheers!
you can force php to pass things by reference by adding an &-sign to the parameter. read the documentation for more information.

how to convert object into string in php [duplicate]

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.

Categories