对于一个新数组,我这样做:
$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";
当前回答
你也可以试试这种方法。
<?php
$obj = json_decode("{}");
var_dump($obj);
?>
输出:
object(stdClass)#1 (0) { }
其他回答
我想指出的是,在PHP中,没有像空对象这样的东西:
$obj = new stdClass();
var_dump(empty($obj)); // bool(false)
当然$obj是空的。
另一方面,空数组在两种情况下都是空的
$arr = array();
var_dump(empty($arr));
引用changelog函数为空
没有属性的对象不再被认为是空的。
你有这个不好但有用的技术:
$var = json_decode(json_encode([]), FALSE);
除了僵尸的答案,如果你一直忘记stdClass
function object(){
return new stdClass();
}
现在你可以做:
$str='';
$array=array();
$object=object();
Php.net说它是最好的:
$new_empty_object = new 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