1

I know this is (one of the) proper ways to create an Array of Objects in 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);

but in some other languages (JS, ActionScript..etc) you can quickly create the object inside the array declaration like so:

var userArray = [{name:'name 1', age:'10'}, {name:'name 2', age:'11'}, {name:'name 3', age:'12'}];

generic, not named, no class objects.....

And then access it like so:

userArray[0].name 

Is there a quick/shorthand way in PHP to do the same?

Or do you need to define an object name and instantiate it..etc

Like so: $obj1 = new stdClass;

and then move to assigning each property and then add to the array all in separate steps?

whispers
  • 962
  • 1
  • 22
  • 48

2 Answers2

2

You can declare your array and then simply cast it to an object, e.g.

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

Which will give you this:

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

)
Rizier123
  • 58,877
  • 16
  • 101
  • 156
0

You can declare variables of a class to be public

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);

You can also dynamically create objects like so:

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

Or working with an array of objects:

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;
skrilled
  • 5,350
  • 2
  • 26
  • 48