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";
$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, 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 (ie "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";
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.
链接地址: http://www.djcxy.com/p/23640.html上一篇: Scala中的对象和类之间的区别
下一篇: 如何在PHP中定义一个空对象