对于一个新数组,我这样做:

$aVal = array();

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

对象是否有类似的语法

(object)$oVal = "";

$oVal->key1->var1 = "something";
$oVal->key1->var2 = "something else";

当前回答

我想指出的是,在PHP中,没有像空对象这样的东西:

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

当然$obj是空的。

另一方面,空数组在两种情况下都是空的

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

引用changelog函数为空

没有属性的对象不再被认为是空的。

其他回答

$x = new stdClass();

手册中的一条评论总结得最好:

stdClass是默认的PHP对象。 stdClass没有属性,方法或 的父母。它不支持魔法 方法,并且没有实现接口。 将标量或数组强制转换为 对象的实例 stdClass。你可以使用stdClass 当你需要一个通用对象时 实例。

如果你不想这样做:

$myObj = new stdClass();
$myObj->key_1 = 'Hello';
$myObj->key_2 = 'Dolly';

您可以使用以下其中之一:

PHP > = 5.4

$myObj = (object) [
    'key_1' => 'Hello',
    'key_3' => 'Dolly',
];

PHP < 5.4

$myObj = (object) array(
    'key_1' => 'Hello',
    'key_3' => 'Dolly',
);

你有这个不好但有用的技术:

$var = json_decode(json_encode([]), FALSE);

如果你想创建一个具有动态属性的对象(如javascript),而不接收未定义属性的警告。

class stdClass {

public function __construct(array $arguments = array()) {
    if (!empty($arguments)) {
        foreach ($arguments as $property => $argument) {
            if(is_numeric($property)):
                $this->{$argument} = null;
            else:
                $this->{$property} = $argument;
            endif;
        }
    }
}

public function __call($method, $arguments) {
    $arguments = array_merge(array("stdObject" => $this), $arguments); // Note: method argument 0 will always referred to the main class ($this).
    if (isset($this->{$method}) && is_callable($this->{$method})) {
        return call_user_func_array($this->{$method}, $arguments);
    } else {
        throw new Exception("Fatal error: Call to undefined method stdObject::{$method}()");
    }
}

public function __get($name){
    if(property_exists($this, $name)):
        return $this->{$name};
    else:
        return $this->{$name} = null;
    endif;
}

public function __set($name, $value) {
    $this->{$name} = $value;
}

}

$obj1 = new stdClass(['property1','property2'=>'value']); //assign default property
echo $obj1->property1;//null
echo $obj1->property2;//value

$obj2 = new stdClass();//without properties set
echo $obj2->property1;//null

你也可以通过解析JSON得到一个空对象:

$blankObject= json_decode('{}');