我搜索一个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'}
有谁知道这个功能名称?
答案 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');