【发布时间】:2015-07-21 22:22:46
【问题描述】:
我知道这是在 PHP 中创建对象数组的(其中一种)正确方法:
$obj1 = new stdClass;
$obj1->title = "Title 1";
$obj1->author = "Author 1";
$obj1->publisher = "Publisher Name 1";
$obj2 = new stdClass;
$obj2->title = "Title 2";
$obj2->author = "Author 2";
$obj2->publisher = "Publisher Name 2";
$obj3 = new stdClass;
$obj3->title = "Title 3";
$obj3->author = "Author 3";
$obj3->publisher = "Publisher Name 3";
$newArray = array($obj1, $obj2, $obj3);
echo ($newArray[0]->title);
但在其他一些语言(JS、ActionScript..etc)中,您可以像这样在数组声明中快速创建对象:
var userArray = [{name:'name 1', age:'10'}, {name:'name 2', age:'11'}, {name:'name 3', age:'12'}];
通用,未命名,无类对象.....
然后像这样访问它:
userArray[0].name
在 PHP 中是否有快速/简写的方法来做同样的事情?
或者你需要定义一个对象名称并实例化它..etc
像这样:$obj1 = new stdClass;
然后转移到分配每个属性,然后在单独的步骤中添加到数组中?
【问题讨论】:
标签: php arrays object shorthand