在 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';
(注意:new Object
与 Javascript 中的 {}
相同)
关于php - PHP 中类似 Javascript 的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4401623/