php 可以将方法用作 array_map 函数吗

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1077491/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 00:52:58  来源:igfitidea点击:

Can a method be used as an array_map function

phpmethodsarray-map

提问by allyourcode

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?

但是 array_map 的第一个参数应该是函数的名称。我想避免围绕 $instance->fun 编写包装函数,但这似乎不可能。真的吗?

回答by Jani Hartikainen

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

是的,您可以对方法进行回调,如下所示:

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

see the callback typein PHP's manual for more info

有关更多信息,请参阅PHP 手册中的回调类型

回答by Metronom

You can also use

你也可以使用

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

syntax.

句法。

回答by lijinma

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

其实你需要知道Callback的定义,请参考以下代码:

<?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

来自:http: //php.net/manual/en/language.types.callable.php