How to define an empty object in PHP


with a new array I do this:

$aVal = array();

$aVal[key1][var1] = "something";
$aVal[key1][var2] = "something else";

Is there a similar syntax for an object

(object)$oVal = "";

$oVal->key1->var1 = "something";
$oVal->key1->var2 = "something else";
5/29/2017 1:01:47 PM

Accepted Answer

$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.

9/17/2009 6:07:49 AM

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

$oVal = new stdClass();

But, with PHP >= 5.4, 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!"...).

The same with PHP < 5.4 is:

$oVal = (object) array();

(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.

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"; // PHP creates  a Warning here
$oVal->key1->var2 = "something else";

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

Warning: Creating default object from empty value

This could be a problem if your configuration (see error reporting level) shows this warning to the browser. This is another entire topic, but a quick and dirty approach could be using the error control operator (@) to ignore the warning:

$oVal = new stdClass();
@$oVal->key1->var1 = "something"; // the warning is ignored thanks to @
$oVal->key1->var2 = "something else";

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow