PHP对象数组(速记)

时间:2015-07-21 22:22:46

标签: php arrays object shorthand

我知道这是(用于在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;

然后移动到分配每个属性,然后在不同的步骤中添加到数组?

2 个答案:

答案 0 :(得分:2)

您可以声明您的数组,然后只需cast声明一个对象,例如

$arr = [
    (object) [
               "a" => 1,
               "b" => 2,
               "c" => 3,
    ]
];

哪个会给你这个:

Array
(
    [0] => stdClass Object
        (
            [a] => 1
            [b] => 2
            [c] => 3
        )

)

答案 1 :(得分:0)

您可以将类的变量声明为公共

class Movie {
  public $name = 'Some Title';
  public $description = 'This is a description'
}

$movie = new Movie;
echo $movie->name;
echo $movie->description;

$movie->name = 'Name here';
$movie->description = 'New Description';

var_dump($movie);

您还可以动态创建对象:

$movie = (object) array('name'=>'Okay','description'=>'here we go again');
echo $movie->name;
echo $movie->description;

或使用一组对象:

for($i=1;$i<=5;$i++) {
   $movies[] = (object) array('name'=>'Movie #'.$i, 'description'=>'This is movie number '.$i);
}
echo $movies[1]->name;
echo $movies[1]->description;