在JS中创建对象的方式非常方便,可以这样写:
test = { foo : { bar : "hello world" }, bar2 : "hello world 2" }
然后像这样使用它们:
test.foo.bar
test.bar2
在PHP中是否有类似于这样的东西,而不需要声明类?
在JS中创建对象的方式非常方便,可以这样写:
test = { foo : { bar : "hello world" }, bar2 : "hello world 2" }
然后像这样使用它们:
test.foo.bar
test.bar2
在PHP中是否有类似于这样的东西,而不需要声明类?
它被称为关联数组。
示例(注意:缩进是为了排版):
$test = array(
'foo' => array(
'bar' => 'hello world'
),
'bar2' => 'hello world 2'
);
$test['foo']['bar'];
$test['bar2'];
这相当于以下的Javascript代码:
var test = {
'foo': {
'bar': 'hello world',
},
'bar2': 'hello world 2'
};
作为替代方案,您可以使用预先声明的StdClass。
$test = new StdClass;
$test->foo = new StdClass;
$test->foo->bar = 'hello world';
$test->bar2 = 'hello world 2';
这将用JavaScript编写为:
var test = new Object;
test.foo = new Object;
test.foo.bar = 'hello world';
test.bar2 = 'hello world 2';
(注意:在JavaScript中,new Object
与{}
相同)
stdClass允许您创建(实质上)无类型的对象。例如:
$object = (object) array(
'name' => 'Trevor',
'age' => 42
);
如下所示,创建stdClass对象的最快方法是转换关联数组。对于多个级别,您只需再次在内部执行相同的操作,如下所示:
$object = (object) array(
'name' => 'Trevor',
'age' => '42',
'car' => (object) array(
'make' => 'Mini Cooper',
'model' => 'S',
'year' => 2010
)
);
另一种方法是使用递归函数将关联数组转换为对象。下面是一个示例。
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);
当你不是创建关联数组的人时,这很有用。
不幸的是,尽管PHP 5.3支持匿名方法,但您无法将匿名方法放入stdClass中(尽管可以将其放入关联数组中)。 但无论如何,这并不太糟糕;如果您想在其中实现功能,真的应该创建一个类。
->
运算符来访问值,否则仅使用关联数组更有效率。我认为你要找的是一个 关联数组
$test["foo"]["bar"]
http://www.google.com/search?sourceid=chrome&ie=UTF-8&q=keyed+arrays
test
是一个常量。它应该是$test
。 - Lekensteyn最接近的东西应该是数组。
$test = array(
'foo' => array('bar' => 'hello world'),
'bar2' => 'hello world 2',
);
echo $test['foo']['bar'];
从技术上讲,不是必需的。但是如果您正在创建一个数据对象(即没有方法),您可以从技术上编写一个 JSON 字符串并使用它。
$obj = json_decode($obj_string);
我不建议这样做。我认为会有显著的速度损失。
编辑 虽然不用特别提醒,但应该使用关联数组来代替平面数据对象。
json_decode
将不会返回任何内容,因为它是无效的Json。 - Gordon$a = array(
'a'=> 123,
'b'=> 334,
'c'=> 7853
);
echo json_encode($a);
{"a":123,"b":334,"c":7853}