PHP Error, is it resolvable, or a language bug? - php

Given the following code
$c= new SoapClient('http://www.webservicex.net/CurrencyConvertor.asmx?WSDL');
$usa = "USD";
$eng = "GBP";
doing a __getTypes on the client gives me
Array ( [0] => struct ConversionRate { Currency FromCurrency; Currency ToCurrency; } [1] => string Currency [2] => struct ConversionRateResponse { double ConversionRateResult; } )
if i then do
$calculation = $c->ConversionRate($usa, $eng);
and print calculation i get an error about
Catchable fatal error: Object of class stdClass could not be converted to string
Is there a specific way i should be printing this out, or i it a bug, from researching / googling many people seem to have a problem but i cant find a suitbale solution, other than downgrading php, which isnt a solution for me as i am doing this as homework and its running off of a college server

I'm guessing the return type from that function is not a string (or anything with __toString defined). Normally instances of stdClass will have one or more properties which will be of use to you.
Try doing something like:
print_r($calculation)
That should tell you what the object has on it, and what it is you might want to do with it. I'd guess you'd want to be printing some property off there along the lines of (example):
echo $calculation->result;

Try passing the parameters as an array:
$parameters = array('FromCurrency' => "USD",
'ToCurrency' => "GBP");
$calculation = $soapClient->ConversionRate($parameters)
var_dump($calculation);
var_dump() could highlight that your result is an object and the double could be a member of that object.
Example:
$calculation->ConversionRateResult;

Related

php: call a method of an object coming from an array

I'm trying to figure out a way to call a method of a specified member (Class A) coming from an array of members in class B.
<?php
class A
{
public function do_something()
{
echo "class A did something";
}
}
class B
{
private $arr = array();
private $current_index = 0;
public function add_new_A()
{
$new_a = new A;
array_push($this->arr, (object) [
$this->current_index => $new_a
]);
$this->current_index++;
}
public function get_an_A_by_index($index)
{
return $this->arr{$index};
}
public function do_something_with_A_member_inside_array($index)
{
self::get_an_A_by_index($index)->do_someting();
}
}
$b = new B;
$b->add_new_a();
$b->add_new_a();
echo print_r($b->get_an_A_by_index(0));
echo "\n";
$b->do_something_with_A_member_inside_array(0); // returns error
// console:
// stdClass Object ( [0] => A Object ( ))
// Uncaught Error: Call to undefined method stdClass::do_something();
?>
To wrap things up, I want to know if my approach is considered bad and/or if there is something I can do to fix the error. Before you disagree with my code, take a look at my php code I'm actually working on. That's all for my question.
Now about why I want to call a method of a member A inside . For my assignment I want a program that does something seperately with the method do_something of class a. So far, the only way to do that is by storing seperate members of A.
I'm not sure if I'm approaching this wrong or not, because I'm coming from Java. So, The first thing I came up with was the approach shown above. When I do this in Java, it works fine. But php is different from Java and I'm still learning how php works since I'm new to it.
Your code isn't far off, you've just got an issue with the way you're building up the collection of A objects.
array_push($this->arr, (object) [
$this->current_index => $new_a
]);
This is creating a data structure that I'm pretty sure isn't what you expect. You'll end up with an array full of stdClass objects, each with a single A member and its own internal index:
Array
(
[0] => stdClass Object
(
[0] => A Object
(
)
)
)
You're then retrieving the stdClass object and trying to run the method on that, hence the Call to undefined method stdClass::do_something... error you're seeing.
Instead, all you need to do is this:
$this->arr[$this->current_index] = $new_a;
The rest of your code is just expecting an array of A objects, nothing nested any deeper.
I've put a full example here: https://3v4l.org/ijvQa. Your existing code had a couple of other typos, which are also fixed. You'll spot them easily enough if you turn on error reporting.

Why stdClass is coming instead of our custom object name?

Here My class name is User, When I print my class properties I'm getting my objective name properly. After that, I encoded the data with json_encode(). and then I decoding with json_decode(). I'm getting stdClass objective why?
<?php
class User
{
public $name;
public $age;
public $salary;
}
$user = new User();
$user->name = 'Siddhu';
$user->age = 24;
$user->salary = 7000.80;
print_r($user);
//Output: User Object ( [name] => Siddhu [age] => 24 [salary] => 7000.8 )
print_r(json_encode($user));
//Output: {"name":"Siddhu","age":24,"salary":7000.8}
$d = json_encode($user);
$s = json_decode($d);
print_r($s);
//Output: stdClass Object ( [name] => Siddhu [age] => 24 [salary] => 7000.8 )
If you noticed stdClass is coming, How can I change to user
There is no direct way you can get data in class object either you need to used custom method to decode else you can use serialize() && unserialize() function to get data in the class object when you decode;
$serialized_user_object = serialize($user);
$deserialized_user_object = unserialize($serialized_user_object);
In json_decode you can pass true in second argument if you want data as array.
like this.
var_dump(json_decode($json, true));
to know more about json_decode see here.
The reason this happens can be demonstrated quite easily...
class foo{
public $bar = 'bar';
}
$json = json_encode(new foo);
echo $json."\n\n";
print_r(json_decode($json));
Output
{"bar":"bar"}
stdClass Object
(
[bar] => bar
)
Sandbox
As you can see the output {"bar":"bar"} contains no information about what if any class this was, it could have been ['bar'=>'bar'] and the JSON would be the same... Then when decoding it, you don't have json_decode set to return as an array (second argument set to true), which is fine as that's not really what you want, but when it's set that way you get stdClass objects instead of an associative array for items with non-numeric keys. In short there is no way to recover the class "foo" from the json {"bar":"bar"} as that information does't exist (you can make it exist, but that's another tale for another day).
Using serialize we get something very different.
class foo{
public $bar = 'bar';
}
$json = serialize(new foo);
echo $json."\n\n";
print_r(unserialize($json));
Output
O:3:"foo":1:{s:3:"bar";s:3:"bar";}
foo Object
(
[bar] => bar
)
Sandbox
This O:3:foo means an Object with a class name 3 in length named "foo". So it preserves that information for PHP to use when "decoding" the data.
The whole thing reads like this:
Object (3) "foo" with 1 property named (s)tring (3) "bar" with a value of (s)tring (3) "bar", or something like that.
Make sense.
AS a note PHP's serialize is less portable then JSON, as it only works in PHP, It's also much harder to manually edit then JSON, but if you really want to encode a class than that is the easiest way to do it. That said you can also "repopulate" the class from JSON data, but that can also be hard to maintain.

How to work with not standart named array in object

I don't know how to work with such object, i need to get first and second one status value, tryed to convert it to json, but it gives me nothing. I just don't get it how to open array with such "_data:MailWizzApi_Params:private" name.
Source:
// SEARCH BY EMAIL
$response = $endpoint->emailSearch($myConfig["LIST-UNIQUE-ID"], $_GET["email"]);
// DISPLAY RESPONSE
echo '<hr /><pre>';
print_r($response->body);
echo '</pre>';
I receive such answer
MailWizzApi_Params Object
(
[_data:MailWizzApi_Params:private] => Array
(
[status] => success
[data] => Array
(
[subscriber_uid] => an837jdexga45
[status] => unsubscribed
)
)
[_readOnly:MailWizzApi_Params:private] =>
)
In this case, you can't.
Because it's private field.
For public fields with "incorrect" names you can use snippet:
$name = '}|{';
$obj->$name;
So, let see to your property: [_data:MailWizzApi_Params:private].
It is private field of instance of MailWizzApi_Params class with _data name.
Let's google to it's implementation: Found
As you can see it has toArray public method. Just use it.
print_r($response->body->toArray());
It has ArrayAccess implemented also. So, $response->body['status'] or $response->body['data'] will works.
Thank you guys for fast answers, here is my dumb way if reading status value
(thanks, #Jose Manuel Abarca Rodríguez)
$toJson = json_encode((array)$response->body);
$toJson = str_replace(array("\u0000MailWizzApi_Params\u0000_"), "", $toJson);
So we receive a normal json:
{"data":{"status":"success","data":{"subscriber_uid":"an837jdexga45","status":"unsubscribed"}},"readOnly":false}
And now we need just to decode it
$json = json_decode($toJson, true);
echo $json['data']['status'];

PHP doesn't find array elements

A library I use uses an array. Applying print_r to that array prints this:
Array
(
[*queueId] => 1
[*handle] => 9b875867b36d568483fb35fdb8b0bbf6
[*body] => First string in the TestQueue
[*md5] => c23ba714199666efbc1dcd5659bb0a0a
[*timeout] => 1408003330.6534
[*id] => 2
[*creationdate] => 2014-08-13 16:03:37
)
The library uses a magic getter on that array
public function __get($key)
{
if (!array_key_exists($key, $this->_data)) {
throw new Exception\InvalidArgumentException("Specified field \"$key\" is not in the message");
}
return $this->_data[$key];
}
When I try to access
$myObject->body
I run into the exception. In fact, the debugger shows that array_key_exists will return false while the _data array is available as printed above
The asterisk indicates that this array is a representation of an object, probably the original object property is protected.
http://php.net/manual/en/language.types.array.php#language.types.array.casting
As I explained in the comments, the array keys actually start with an asterisk. Since you can't call them using the regular syntax of $obj->*body (it'll cause a syntax error), you can use the following:
$myObject->{'*body'}
This should solve your problem.
Assuming that $myObject is the array you are talking from:
You can't access arrays with ->, use $myObject['*body'] instead. (And you should as well change the name to $myArray, for example)
As #MarkBaker stated in the comment of my question, the problem was that I was serializing an object with private properties to the array. The asterisk were marks that these properties were private.

how can I read object values and atributes with php?

Ive been working with some code and I am recieving a var (I didnt work the entire code, so, I dont know how it was made), my problem is that I get something like this
AdminUserRoleDecorator Object (
[user:AdminUserRoleDecorator:private] => EssUserRoleDecorator Object (
[user:EssUserRoleDecorator:private] => User Object (
[topMenuItemsArray:User:private] => Array ( )
[employeeList:User:private] => Array ( )
[activeProjectList:User:private] => Array ( )
[empNumber:User:private] => [allowedActions:User:private] => Array ( )
[nextState:User:private] => [userId:User:private] => 1
[userTimeZoneOffset:User:private] => -6
To be honest, and It could sound like a very stupid question, I dont know how to read that, normally I get the atributes in the way $myobject->atribute , now this I really have no idea, any way I can access to this? for example, I want to get the userId, I see its there, with :user:private (which I also dont know what are they for).
If I try
$myobject->User;
for example, I get nothing back.
Thanks.
EDIT:
I tried $myobject->user
and I am getting this
Fatal error: Cannot access private property AdminUserRoleDecorator
I am working with symfony by the way.
From the answer I gave here, you can get some insight into objects with get_class_methods() (php reference) and get_class_vars(). On that post, I made up a function to help me learn more about class methods available:
show_methods($playlistListFeed);
function show_methods( $_a ) {
echo "<h3>Methods for ".get_class($_a)."</h3>";
$_a= get_class_methods($_a);
$_a=array_unique($_a);
array_multisort(&$_a);
$i=0;
foreach( $_a as $method ) {
$i++;
printf("%-30.30s",$method);
if($i%5==0)
echo "\n";
}
}

Categories