views:

95

answers:

4

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 ?

+2  A: 

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

$a = (object)array('name' => 'john', 'age' => 13);
echo $a->name; // 'john'
Crescent Fresh
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
@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
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
A: 

Casting to object works:

$a = (object)array('name' => 'john', 'age' => 13);

Thank you !

Florin
Hi Florin. If you want to add thanks or a comment to an answer, it's best done as a comment rather than another 'answer'
adam
+1  A: 

You can also do:

$a = new stdClass;
$a->name = 'john';
$a->age = 13;
ceejayoz
A: 

Another way:

$text = '{"name": "john", "age": 13}';
$obj = json_decode($text);
David Barnes