How to define an empty object in PHP
Solution 1:
$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.
Solution 2:
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",
],
];