PHP Reference ยท Standard PHP Library and Classes
The stdClass class
Reference for PHP stdClass: create generic objects, convert arrays with (object), read json_decode() results, and why dynamic properties on other classes are deprecated.
stdClass is PHP's empty, general-purpose class. It has no properties or methods of its own, and you can add properties to it freely. It is what json_decode() returns for JSON objects (without the associative flag) and what an (object) cast produces from an array.
Use it for quick bags of data, such as decoded JSON. For anything with rules, such as validation or behavior, write a real class.
$point = new stdClass(); $point->x = 3; $point->y = 4;
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
$obj = new stdClass(); $obj = (object) $array; $obj = json_decode($json); // JSON objects become stdClass
stdClass has no constructor parameters and no methods.
| Name | Description |
|---|---|
(object) $value |
Casts an array to stdClass (keys become property names). A scalar becomes an object with a scalar property; null becomes an empty object. |
(array) $object |
Casts back to an array; for plain stdClass objects the property names become keys. |
Return value: a new stdClass instance.
Usage notes
- Dynamic properties are allowed here. Since PHP 8.2, creating undeclared properties on your own classes is deprecated, but
stdClassis exempt. - Reading a missing property gives a warning ("Undefined property") and
null. Check withisset()or use$o->x ?? null. - Objects are handles. Assigning one to another variable shares it; use
clonefor a shallow copy. Nested objects are still shared afterclone. - Casting is shallow.
(object) $arraydoes not convert nested arrays, so$obj->metastays an array in the second example. - Numeric keys:
(object) [1, 2]gives properties named"0"and"1", readable as$o->{'0'}. json_decode()returnsstdClassby default; passtrueas the second argument (orJSON_OBJECT_AS_ARRAY) to get associative arrays, which are usually easier to validate.- Not a base class. Classes do not extend
stdClassautomatically, and$x instanceof stdClassis false for your own classes. - Prefer typed classes (for example with constructor promotion and
readonly) once the data has a known shape.
Related
json_decode(),JsonSerializable,ArrayObject- Lessons: Classes and objects, JSON