6

Is it it possible to do this in php?

Javascript code:

var a = {name: "john", age: 13}; //a.name = "john"; a.age = 13

Instantiate the stdClass variable on the fly ?

Stéphane
  • 3,884
  • 1
  • 30
  • 27
Florin
  • 63
  • 1
  • 3

3 Answers3

10

Try using the associative array syntax, and casting to object:

$a = (object)array('name' => 'john', 'age' => 13);
echo $a->name; // 'john'
Crescent Fresh
  • 115,249
  • 25
  • 154
  • 140
  • 1
    Casting seems the best method, but i think you cast it to (object) rather than (stdClass) as per http://php.net/manual/en/language.types.type-juggling.php – Adam Hopkinson Oct 29 '09 at 17:47
  • @adam: right you are. Did `stdClass` use to work or something? I have it in my head that it did work once upon a time. – Crescent Fresh Oct 29 '09 at 18:00
  • I think php always reports objects as stdClass (with var_dump, etc) but the actual type is object. Should be the same in both directions, if you ask me. – Adam Hopkinson Oct 29 '09 at 22:37
5

You can also do:

$a = new stdClass;
$a->name = 'john';
$a->age = 13;
ceejayoz
  • 176,543
  • 40
  • 303
  • 368
1

Another way:

$text = '{"name": "john", "age": 13}';
$obj = json_decode($text);
David Barnes
  • 2,138
  • 5
  • 19
  • 25