方法可以用作 array_map 函数吗

我想这样做:

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

但是 array _ map 的第一个参数应该是函数的名称。我想避免写一个关于 $instance-> fun 的包装函式,但这似乎是不可能的。是真的吗?

47168 次浏览

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

You can also use

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

syntax.

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

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);
}