对于一个新数组,我这样做:
$aVal = array();
$aVal[key1][var1] = "something";
$aVal[key1][var2] = "something else";
对象是否有类似的语法
(object)$oVal = "";
$oVal->key1->var1 = "something";
$oVal->key1->var2 = "something else";
对于一个新数组,我这样做:
$aVal = array();
$aVal[key1][var1] = "something";
$aVal[key1][var2] = "something else";
对象是否有类似的语法
(object)$oVal = "";
$oVal->key1->var1 = "something";
$oVal->key1->var2 = "something else";
当前回答
你可以使用new stdClass()(这是推荐的):
$obj_a = new stdClass();
$obj_a->name = "John";
print_r($obj_a);
// outputs:
// stdClass Object ( [name] => John )
或者你可以将一个空数组转换为一个对象,该对象会生成stdClass内置类的一个新的空实例:
$obj_b = (object) [];
$obj_b->name = "John";
print_r($obj_b);
// outputs:
// stdClass Object ( [name] => John )
或者你可以将空值转换为一个对象,该对象会生成stdClass内置类的一个新的空实例:
$obj_c = (object) null;
$obj_c->name = "John";
print($obj_c);
// outputs:
// stdClass Object ( [name] => John )
其他回答
$x = new stdClass();
手册中的一条评论总结得最好:
stdClass是默认的PHP对象。 stdClass没有属性,方法或 的父母。它不支持魔法 方法,并且没有实现接口。 将标量或数组强制转换为 对象的实例 stdClass。你可以使用stdClass 当你需要一个通用对象时 实例。
这里有一个迭代的例子:
<?php
$colors = (object)[];
$colors->red = "#F00";
$colors->slateblue = "#6A5ACD";
$colors->orange = "#FFA500";
foreach ($colors as $key => $value) : ?>
<p style="background-color:<?= $value ?>">
<?= $key ?> -> <?= $value ?>
</p>
<?php endforeach; ?>
你有这个不好但有用的技术:
$var = json_decode(json_encode([]), FALSE);
除了僵尸的答案,如果你一直忘记stdClass
function object(){
return new stdClass();
}
现在你可以做:
$str='';
$array=array();
$object=object();
如果你想创建一个具有动态属性的对象(如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