题
我想做的事情是这样的:
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的第一个参数被认为是该函数的名称。我想避免周围实例 - $>乐趣写的包装功能,但它似乎并不像这是可能的。是真的吗?
解决方案
其他提示
您还可以使用
array_map('Class::method', $array)
语法。
其实,你需要知道回调的定义,请您参考下面的代码:
<?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
?>
不隶属于 StackOverflow