使用array_map返回实例化对象的数组?

时间:2011-08-08 16:33:31

标签: php object instantiation array-map

说我有以下内容:

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

     return $this;
   }
}

现在给出一个ID数组,我想最终得到一个实例化的数组。如下所示:

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

当然,Thing类没有“新”方法,“__construct”也不受限制。我知道这可以通过循环$ ID的额外步骤来完成,但是有没有一种方法可以在每个使用array_map上调用“new Thing($ id)”?

3 个答案:

答案 0 :(得分:8)

它不起作用,因为没有静态方法Thing::new。您可以添加它或只提供array_map回调功能:

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

答案 1 :(得分:2)

$things = array();
foreach($ids as $id)
   $things[] = new Thing($id);
这是php的做事方式。这就是php语言的工作原理。如果您喜欢函数式编程,迭代器,理解和其他smartxxx技巧,请考虑使用其他语言。

要回答你的问题字面意思,你需要两个小功能

// replacement for "new"
function init($klass /* , param, param */) {
    $c = new ReflectionClass($klass);
    return $c->newInstanceArgs(
        array_slice(func_get_args(), 1));
}

// generic currying
function curry($fn /* , param, param */) {
    $_ = array_slice(func_get_args(), 1);
    return function() use($fn, $_) {
        return call_user_func_array($fn, 
            array_merge($_, func_get_args()));
    };
}

然后

class Thing
{
    function __construct($x, $y) {
        $this->x = $x;
        $this->y = $y;
    }
}

// curry one param
print_r(array_map(
    curry("init", "Thing"),
    array("x1", "x2", "x3"),
    array("y1", "y2", "y3")
));

// curry two params
print_r(array_map(
    curry("init", "Thing", "x"),
    array("y1", "y2", "y3")
));

值得吗?我不这么认为。

答案 2 :(得分:0)

对于它的外观,你试图检查是否已经启动了一个对象/类。

您可以尝试get_declared_classes()功能。 if将返回一个实例化所有类的数组。

使用此数组,您可以检查系统中是否已知您的类,如果不是,您可以动态启动它。