Can a method be used as an array_map function

PhpMethodsArray Map

Php Problem Overview


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?

Php Solutions


Solution 1 - Php

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

Solution 2 - Php

You can also use

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

syntax.

Solution 3 - Php

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionallyourcodeView Question on Stackoverflow
Solution 1 - PhpJani HartikainenView Answer on Stackoverflow
Solution 2 - PhpMetronomView Answer on Stackoverflow
Solution 3 - PhplijinmaView Answer on Stackoverflow