How to define an empty object in PHP How to define an empty object in PHP php php

How to define an empty object in PHP


$x = new stdClass();

A comment in the manual sums it up best:

stdClass is the default PHP object. stdClass has no properties, methods or parent. It does not support magic methods, and implements no interfaces.

When you cast a scalar or array as Object, you get an instance of stdClass. You can use stdClass whenever you need a generic object instance.


The standard way to create an "empty" object is:

$oVal = new stdClass();

But I personally prefer to use:

$oVal = (object)[];

It's shorter and I personally consider it clearer because stdClass could be misleading to novice programmers (i.e. "Hey, I want an object, not a class!"...).


(object)[] is equivalent to new stdClass().

See the PHP manual (here):

stdClass: Created by typecasting to object.

and here:

If an object is converted to an object, it is not modified. If a value of any other type is converted to an object, a new instance of the stdClass built-in class is created.

and here (starting with PHP 7.3.0, var_export() exports an object casting an array with (object)):

Now exports stdClass objects as an array cast to an object ((object) array( ... )), rather than using the nonexistent method stdClass::__setState(). The practical effect is that now stdClass is exportable, and the resulting code will even work on earlier versions of PHP.


However remember that empty($oVal) returns false, as @PaulP said:

Objects with no properties are no longer considered empty.

Regarding your example, if you write:

$oVal = new stdClass();$oVal->key1->var1 = "something"; // this creates a warning with PHP < 8                                 // and a fatal error with PHP >=8$oVal->key1->var2 = "something else";

PHP < 8 creates the following Warning, implicitly creating the property key1 (an object itself)

Warning: Creating default object from empty value

PHP >= 8 creates the following Error:

Fatal error: Uncaught Error: Undefined constant "key1"

In my opinion your best option is:

$oVal = (object)[  'key1' => (object)[    'var1' => "something",    'var2' => "something else",  ],];


I want to point out that in PHP there is no such thing like empty object in sense:

$obj = new stdClass();var_dump(empty($obj)); // bool(false)

but of course $obj will be empty.

On other hand empty array mean empty in both cases

$arr = array();var_dump(empty($arr));

Quote from changelog function empty

Objects with no properties are no longer considered empty.