PHP:从海关对象功能获取数组

时间:2014-08-13 09:43:30

标签: php arrays object

我搜索一个php函数,它将执行以下过程:

class Item{

private $id;

public function __construct($id){
    $this->id = $id
}

public function foo(){
    return 'Item_'.$this->id;
}
}

my_array = array();
$my_array[] = new Item(1);
$my_array[] = new Item(2);
$results = thefunctionimlookingfor($my_array, 'foo');

//which give :
//$results = {'Item_1', 'Item_2'}

有谁知道这个功能名称?

1 个答案:

答案 0 :(得分:1)

$results = array_map(function(Item $item) { return $item->foo(); }, $my_array);

如果你真的需要这个功能:

function applyMethod($data, $method) {
    return array_map(function($item) use ($method) {
        return $item->$method();
    }, $data);
}

$result = applyMethod($my_array, 'foo');