84

I want to do something like this:

class Cls {
  function fun($php) {
    return 'The rain in Spain.';
  }
}

$ar = array(1,2,3);
$instance = new Cls();
print_r(array_map('$instance->fun', $ar));
               // ^ this won't work

but the first argument to array_map is supposed to be the name of the function. I want to avoid writing a wrapper function around $instance->fun, but it doesn't seem like that's possible. Is that true?

AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
allyourcode
  • 21,871
  • 18
  • 78
  • 106

4 Answers4

188

Yes, you can have callbacks to methods, like this:

array_map(array($instance, 'fun'), $ar)

see the callback type in PHP's manual for more info

chiborg
  • 26,978
  • 14
  • 97
  • 115
Jani Hartikainen
  • 42,745
  • 10
  • 68
  • 86
  • 34
    If the method is static array('Class', 'StaticMethod') works too – Philippe Gerber Jul 03 '09 at 02:07
  • 1
    what if its an abstract class? which has the function to be called. – amitchhajer Apr 25 '13 at 06:47
  • 4
    @amitchhajer if it's a static function, you can use `array('Class_Name', 'functionName')` as the parameter. If it's the current class' parent class, then using `array($this, 'functionName')` should most likely work. – Jani Hartikainen Apr 25 '13 at 13:48
  • This does not work for me at all. `$instance` is undefined and `$this` uses the the object I'm calling `array_map from`. Could not find any way (except with a wrapper function) to refer to the objects in my array (I'm on php 5.4.7). – kratenko May 31 '13 at 13:15
  • @kratenko So you have an array containing objects, and you want to call a method on each of those? If so, that isn't something that can be done using array_map like this (or any other array function), as there is no way to refer to each object in the array. – Jani Hartikainen May 31 '13 at 22:40
  • @JaniHartikainen Thanks for clearing that. It looked to me as if that was, what the OP wanted to do. I ended up using a loop. – kratenko Jun 03 '13 at 15:15
  • if you're using namespaces, don't forget to use the full namespace. the following worked for me for static method: array_map('\App\Http\Response\AbstractResponse::convertBakedGood', $bakedGoods) – keisar Apr 23 '15 at 14:31
  • If called from inside a static class use: *array('self', 'functionName')* – Hexodus Nov 15 '15 at 19:11
  • Alternate if it's inside a static class: `array(__CLASS__, 'functionName');` – random_user_name Feb 20 '17 at 21:54
  • what if the function `fun` requires more than 1 params? how to pass those extra params? – Muhammad Omer Aslam Sep 21 '19 at 22:06
45

You can also use

array_map('Class::method', $array) 

syntax.

Sirko
  • 72,589
  • 19
  • 149
  • 183
Metronom
  • 459
  • 4
  • 2
11

Actually, you need to know the definition of Callback, please kindly refer to the following code:

<?php 

// An example callback function
function my_callback_function() {
    echo 'hello world!';
}

// An example callback method
class MyClass {
    static function myCallbackMethod() {
        echo 'Hello World!';
    }
}

$myArray = [1, 2, 3, 4];

// Type 1: Simple callback
array_map('my_callback_function', $myArray); 

// Type 2: Static class method call
array_map(array('MyClass', 'myCallbackMethod'), $myArray); 

// Type 3: Object method call
$obj = new MyClass();
array_map(array($obj, 'myCallbackMethod'), $myArray);

// Type 4: Static class method call (As of PHP 5.2.3)
array_map('MyClass::myCallbackMethod', $myArray);

// Type 5: Relative static class method call (As of PHP 5.3.0)
class A {
    public static function who() {
        echo "A\n";
    }
}

class B extends A {
    public static function who() {
        echo "B\n";
    }
}

array_map(array('B', 'parent::who'), $myArray); // A
?>

From: http://php.net/manual/en/language.types.callable.php

Koen.
  • 25,449
  • 7
  • 83
  • 78
lijinma
  • 2,914
  • 1
  • 23
  • 22
1

It worked for me as follows

<?php
class ExcelAutoFilterController extends Controller
{
    public function transpose($value):array
        {
            return [$value];
        }

        public function generateExcelDropdownDownload($file = 'helloWorld.xlsx')
        {

            $countries = [0 => "Algeria"1 => "Angola"2 => "Benin"3 => "Botswana"4 => "Burkina"5 => "Burundi"6 => "Cameroon"7 => "Cape Verde"8 => "Central African Republic"9 => "Chad"10 => "Comoros"11 => "Congo"12 => "Congo, Democratic Republic of"13 => "Djibouti"14 => "Egypt"15 => "Equatorial Guinea"16 => "Eritrea"17 => "Ethiopia"18 => "Gabon"19 => "Gambia"20 => "Ghana"21 => "Guinea"22 => "Guinea-Bissau"23 => "Ivory Coast"24 => "Kenya"25 => "Lesotho"26 => "Liberia"27 => "Libya"28 => "Madagascar"29 => "Malawi"30 => "Mali"31 => "Mauritania"32 => "Mauritius"];

            $countries = array_map('self::transpose', $countries);
        }
        
Akbarali
  • 688
  • 7
  • 16