Skip to content
Tutorials Center
My learning

Topics

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.

PHP
$point = new stdClass();
$point->x = 3;
$point->y = 4;

Try it

PHP Creating and changing stdClass objects

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.

PHP Casting between arrays and objects, and JSON

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

PHP
$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 stdClass is exempt.
  • Reading a missing property gives a warning ("Undefined property") and null. Check with isset() or use $o->x ?? null.
  • Objects are handles. Assigning one to another variable shares it; use clone for a shallow copy. Nested objects are still shared after clone.
  • Casting is shallow. (object) $array does not convert nested arrays, so $obj->meta stays an array in the second example.
  • Numeric keys: (object) [1, 2] gives properties named "0" and "1", readable as $o->{'0'}.
  • json_decode() returns stdClass by default; pass true as the second argument (or JSON_OBJECT_AS_ARRAY) to get associative arrays, which are usually easier to validate.
  • Not a base class. Classes do not extend stdClass automatically, and $x instanceof stdClass is false for your own classes.
  • Prefer typed classes (for example with constructor promotion and readonly) once the data has a known shape.