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

$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};

其他回答

使用通用对象并将键值对映射到它。

$oVal = new stdClass();
$oVal->key = $value

或者将数组强制转换为对象

$aVal = array( 'key'=>'value' );
$oVal = (object) $aVal;

如果你想创建一个具有动态属性的对象(如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
$x = new stdClass();

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

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

以类似的方式访问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};

你也可以试试这种方法。

<?php
     $obj = json_decode("{}"); 
     var_dump($obj);
?>

输出:

object(stdClass)#1 (0) { }