-
Notifications
You must be signed in to change notification settings - Fork 19
Associative Arrays vs Objects issue
Pozo edited this page Aug 3, 2011
·
1 revision
###The problem
Since json_encode output always an object when you passing into an associative array, it can cause problem. Take a look for this example:
On server side we have made xyService and xyServiceImpl and one of xyServiceImpl function look like this:
...
function getClassMembersAsAssoc() {
return get_object_vars($object);
}
...
So, when you call on client side this,
$request = $client->call(new RpcRequest('getClassMembersAsAssoc'));
echo '<pre>';
var_dump($request);
echo '</pre>';
The response is not what you expect, altough the get_object_vars returns an associative array of defined object accessible non-static properties.
object(stdClass)#20 (3) {
["jsonrpc"]=>
string(3) "2.0"
["result"]=>
object(stdClass)#21 (2) {
["a"]=>
int(10)
["b"]=>
int(20)
}
["id"]=>
int(1)
}
###The solution
The solution is very easy, when you expect an associative array in response before using you should typecasting the result field, so
$request->result is
object(stdClass)#21 (2) {
["a"]=>
int(10)
["b"]=>
int(20)
}
then (array) $request->result is
array(2) {
["a"]=>
int(10)
["b"]=>
int(20)
}