对于一个新数组,我这样做:
$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";
当前回答
如果你想创建一个具有动态属性的对象(如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
其他回答
使用通用对象并将键值对映射到它。
$oVal = new stdClass();
$oVal->key = $value
或者将数组强制转换为对象
$aVal = array( 'key'=>'value' );
$oVal = (object) $aVal;
stdClass是默认的PHP对象。stdClass没有属性、方法或父类。它不支持魔术方法,也不实现任何接口。
当您将标量或数组强制转换为Object时,您将获得stdClass的实例。只要需要泛型对象实例,就可以使用stdClass。
<?php
// ways of creating stdClass instances
$x = new stdClass;
$y = (object) null; // same as above
$z = (object) 'a'; // creates property 'scalar' = 'a'
$a = (object) array('property1' => 1, 'property2' => 'b');
?>
stdClass不是基类!PHP类不会自动继承任何类。所有的类都是独立的,除非它们显式地扩展另一个类。PHP在这方面不同于许多面向对象的语言。
<?php
// CTest does not derive from stdClass
class CTest {
public $property1;
}
$t = new CTest;
var_dump($t instanceof stdClass); // false
var_dump(is_subclass_of($t, 'stdClass')); // false
echo get_class($t) . "\n"; // 'CTest'
echo get_parent_class($t) . "\n"; // false (no parent)
?>
你不能在你的代码中定义一个名为stdClass的类。该名称已被系统使用。你可以定义一个名为“Object”的类。
您可以定义一个扩展stdClass的类,但是您不会得到任何好处,因为stdClass什么也不做。
(在PHP 5.2.8上测试)
你也可以试试这种方法。
<?php
$obj = json_decode("{}");
var_dump($obj);
?>
输出:
object(stdClass)#1 (0) { }
如果你不想这样做:
$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);