How to instantiate stdClass in place
Asked Answered
B

3

7

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 ?

Beal answered 29/10, 2009 at 17:43 Comment(0)
F
11

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

$a = (object)array('name' => 'john', 'age' => 13);
echo $a->name; // 'john'
Friseur answered 29/10, 2009 at 17:46 Comment(3)
Casting seems the best method, but i think you cast it to (object) rather than (stdClass) as per php.net/manual/en/language.types.type-juggling.phpAvera
@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.Friseur
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.Avera
E
5

You can also do:

$a = new stdClass;
$a->name = 'john';
$a->age = 13;
Eclampsia answered 29/10, 2009 at 18:45 Comment(0)
D
2

Another way:

$text = '{"name": "john", "age": 13}';
$obj = json_decode($text);
Daiseydaisi answered 29/10, 2009 at 21:14 Comment(1)
Requires much more processing than casting an array to an object.Infelicity

© 2022 - 2024 — McMap. All rights reserved.