Search code examples
phpobjectinstantiationarray-map

Use array_map to return an array of instantiated objects?


Say I have the following:

class Thing {
   function __construct($id) {
     // some functionality to look up the record and initialize the object.

     return $this;
   }
}

Now given an array of IDs, I want to end up with an array of instantiated Things. Something like the following:

$ids = array(1, 2, 3, 4, 5);
$things = array_map(array('Thing', 'new'), $ids); // Doesn't work

Of course there is no "new" method for the Thing class, and "__construct" was off limits as well. I know this could be accomplished with extra steps looping through $ids, but is there a slick way of calling "new Thing($id)" on each using array_map?


Solution

  • It can not work, because there is no static method Thing::new. You can either add it or just provide the function as the array_map callback:

    $ids = array(1, 2, 3, 4, 5);
    $things = array_map(function($id){return new Thing($id);}, $ids);