3

Long time, my PHP-application ran on a linux server with apache and PHP.

Now I've set up a windows server with apache and php and simple PHP-Programs have problems.

var_dump($data);
die(var_dump($data['a']));

results in

object(stdClass)#1 (1) { ["a"]=> string(1) "b" } 
Fatal error: Cannot use object of type stdClass as array in BLUB.php on line 14

var_dump says there is an index a. Why does $data['a'] throw an exception?

EDIT: $data is json_decode($something);

feedc0de
  • 3,646
  • 8
  • 30
  • 55

5 Answers5

3

Because its an object, not an array. You cant access it like that. This would be correct:

$data->a;
Realitätsverlust
  • 3,941
  • 2
  • 22
  • 46
  • Why did PHP change that? I think I have an older version of PHP on my linux server. json_decode always produced an array. But I will try that. – feedc0de Apr 02 '14 at 08:08
  • Dont know, but you can still get an array. You have to use `json_decode($something, true);` in that case, then you receive an array, not an object. You can see more here: http://www.php.net/manual/de/function.json-decode.php – Realitätsverlust Apr 02 '14 at 08:12
  • 1
    By the way, who downvoted me? Its not that i really care about up- or downvotes, but you could at least tell me where i did a mistake so i might improve it for the future. – Realitätsverlust Apr 02 '14 at 08:13
  • @DanielBrunner - PHP didn't ___change___ anything (arrays are still arrays), they ___added___ something (objects) – Mark Baker Apr 02 '14 at 08:17
  • @DanielBrunner, you use `json_decode()` which return object, or array if you pass second argument `true` – Barif Apr 02 '14 at 08:19
3

The error contains your answer - $data is actually an object of type stdClass. You could either:

a) access the property 'a' with $data->a or b) typecast $data as an array using (array)$data

Ragdata
  • 1,156
  • 7
  • 16
  • Thanks for the idea with casting it! Now I only have to cast it once and I am able to use my old code. – feedc0de Apr 02 '14 at 08:09
2

As the error says $data is an object, not an array. As such, you want to use object access, rather than array access. In this case, that would be var_dump($data->a)

2

You should use:

 $data = json_decode($something, true);

To get array from json

Barif
  • 1,552
  • 3
  • 17
  • 28
1

since $data in an object you have to access it this way:

$data->a;

Otherwise, you can typecast it to an array and access it actually like an array

$dataArr = (array) $data;

$dataArr['a'];

NOTE

This is possible only whether your object attributes are public

ponciste
  • 2,231
  • 14
  • 16