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

$aVal = array();

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

对象是否有类似的语法

(object)$oVal = "";

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

当前回答

以类似的方式访问stdClass中的数据 对于关联数组,只需使用{$var}语法。

$myObj = new stdClass;
$myObj->Prop1 = "Something";
$myObj->Prop2 = "Something else";

// then to acces it directly

echo $myObj->{'Prop1'};
echo $myObj->{'Prop2'};

// or what you may want

echo $myObj->{$myStringVar};

其他回答

$x = new stdClass();

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

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

如果你想创建一个具有动态属性的对象(如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

Php.net说它是最好的:

$new_empty_object = new stdClass();

创建“空”对象的标准方法是:

$oVal = new stdClass();

但我个人更喜欢用:

$oVal = (object)[];

它更短,我个人认为它更清楚,因为stdClass可能会误导新手程序员(例如。“嘿,我想要一个对象,不是一个类!”…)


(object)[]等价于new stdClass()。

请参阅PHP手册(此处):

stdClass:通过类型转换到对象创建。

在这里:

如果将对象转换为对象,则不修改该对象。如果将任何其他类型的值转换为对象,则会创建stdClass内置类的一个新实例。

这里(从PHP 7.3.0开始,var_export()导出一个使用(object)转换数组的对象):

现在将stdClass对象作为数组导出到对象((对象)数组(…)),而不是使用不存在的方法stdClass::__setState()。实际效果是现在stdClass是可导出的,生成的代码甚至可以在早期版本的PHP上工作。


但是请记住empty($oVal)返回false,正如@PaulP所说:

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

关于你的例子,如果你写:

$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创建以下Warning,隐式创建属性key1(对象本身)

警告:从空值创建默认对象

PHP >= 8创建以下错误:

错误:未定义的常量“key1”

在我看来,你最好的选择是:

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

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

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