Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to instantiate stdClass in place

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 ?

like image 387
Florin Avatar asked Oct 29 '09 17:10

Florin


People also ask

What is new stdClass () in PHP?

The stdClass is the empty class in PHP which is used to cast other types to object. It is similar to Java or Python object. The stdClass is not the base class of the objects. If an object is converted to object, it is not modified.

What is a stdClass?

The stdClass is a generic empty class used to cast the other type values to the object. If a value of any other type is converted to an object, a new instance of the stdClass built-in class is created. The stdClass is not the base class for objects in PHP.


3 Answers

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

$a = (object)array('name' => 'john', 'age' => 13);
echo $a->name; // 'john'
like image 64
Crescent Fresh Avatar answered Oct 05 '22 17:10

Crescent Fresh


You can also do:

$a = new stdClass;
$a->name = 'john';
$a->age = 13;
like image 34
ceejayoz Avatar answered Oct 05 '22 17:10

ceejayoz


Another way:

$text = '{"name": "john", "age": 13}';
$obj = json_decode($text);
like image 35
David Barnes Avatar answered Oct 05 '22 15:10

David Barnes