mvb*_*fst 7 javascript php object
我有个问题.在JS中创建这样的对象非常方便:
test = { foo : { bar : "hello world" }, bar2 : "hello world 2" }
Run Code Online (Sandbox Code Playgroud)
然后像他们一样使用它们
test.foo.bar
test.bar2
Run Code Online (Sandbox Code Playgroud)
在没有声明类的情况下,PHP中是否有类似的东西?
stdClass允许您创建(基本上)无类型对象.例如:
$object = (object) array(
'name' => 'Trevor',
'age' => 42
);
Run Code Online (Sandbox Code Playgroud)
如此处所示,创建stdClass对象的最快方法是转换关联数组.对于多个级别,你只需要在里面再做同样的事情:
$object = (object) array(
'name' => 'Trevor',
'age' => '42',
'car' => (object) array(
'make' => 'Mini Cooper',
'model' => 'S',
'year' => 2010
)
);
Run Code Online (Sandbox Code Playgroud)
另一种方法是使用递归函数将关联数组转换为对象.这是一个例子.
function toObject(array $array) {
$array = (object) $array;
foreach ($array as &$value)
if (is_array($value))
$value = toObject($value);
return $array;
}
// usage:
$array = // some big hierarchical associative array...
$array = toObject($array);
Run Code Online (Sandbox Code Playgroud)
当你不是制作关联数组的人时,这很有用.
不幸的是,即使PHP 5.3支持匿名方法,也不能将匿名方法放入stdClass中(尽管可以将其放入关联数组中).但无论如何这还不错; 如果你想要它的功能,你真的应该创建一个类.
它被称为关联数组.
示例(注意:缩进是出于布局目的):
$test = array(
'foo' => array(
'bar' => 'hello world'
),
'bar2' => 'hello world 2'
);
$test['foo']['bar'];
$test['bar2'];
Run Code Online (Sandbox Code Playgroud)
这相当于以下Javascript代码:
var test = {
'foo': {
'bar': 'hello world',
},
'bar2': 'hello world 2'
};
Run Code Online (Sandbox Code Playgroud)
作为替代方案,您可以使用预先声明的StdClass.
$test = new StdClass;
$test->foo = new StdClass;
$test->foo->bar = 'hello world';
$test->bar2 = 'hello world 2';
Run Code Online (Sandbox Code Playgroud)
这将用JavaScript编写为:
var test = new Object;
test.foo = new Object;
test.foo.bar = 'hello world';
test.bar2 = 'hello world 2';
Run Code Online (Sandbox Code Playgroud)
(注意:new Object和{}Javascript中的相同)