douvcpx6526 2016-05-10 13:42
浏览 51

在所有数组成员上调用对象成员函数

This may be a bit of a silly question and its one of convenience rather than functionality.

Assume we have the class:

class A { 
    public function getId() {
       return rand(0,100); //For simplicity's sake
    }
}

Let's say we have an array of objects of type A, e.g. $array = [ new A(), new A(), new A() ];

Normally if I want to transform the array of all objects into an array of their IDs I'd do something like:

$idArray = array_map(function ($a) { return $a->getId(); }, $array);

However this leaves me with a sort of burning desire to simplify this (I use it quite often). I would like a functionality like:

$idArray = magic_array_map('getId', $array);

My question is, is there a way to call array_map (or similar function) by providing the function name instead of an actual callback? Something akin to array_map('count', $array) but instead of strlen provide a member method name.

In short, is there such a way built-in PHP or do I have to implement an array_map of my own to add this functionality?

  • 写回答

3条回答 默认 最新

  • donglianjiang9321 2016-05-10 13:56
    关注

    You can create your own helper function to do what you want.

    my_map_function($callback, $array) {
        return call_user_func_array(callback, $array);
    }
    
    my_callback_function($array) {
      //TODO
    }
    
    main() {
      $array = [1, 2, 3];
      $array = my_map_function('my_callback_function', $array);
    }
    

    Something like this ;)

    Here you have more information

    评论

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法