使用array_map返回实例化对象的数组? [英] Use array_map to return an array of instantiated objects?

查看:71
本文介绍了使用array_map返回实例化对象的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有以下内容:

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

     return $this;
   }
}

现在给定一个ID数组,我想以一个实例化的事物数组结束.类似于以下内容:

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

对于Thing类,当然没有新"方法,并且"__construct"也不受限制.我知道可以通过循环遍历$ ids的额外步骤来完成此操作,但是是否有一种巧妙的方法可以使用array_map在每个调用"new Thing($ id)"?

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?

推荐答案

它不起作用,因为没有静态方法 Thing :: new .您可以添加它,也可以仅提供函数作为 array_map 回调:

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

这篇关于使用array_map返回实例化对象的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆