This article mainly shares with you the callback function type transfer method in PHP. We test it here through the array_map() function, hoping to help everyone.
Method 1, global function
function foo($val){ return intval($val)+1; } $arr = array('a',2,'b',5,'c',7); //回调函数传递方式 $res = array_map('foo', $arr); /** 输出如下: array (size=6) 0 => int 1 1 => int 3 2 => int 1 3 => int 6 4 => int 1 5 => int 8 */
Method 2, class public function
class Demo { public function foo($val){ return intval($val)+1; } } $arr = array('a',2,'b',5,'c',7); //回调函数传递方式 $res = array_map(array(new Demo, 'foo'), $arr);
Method 3, class private function
class Demo { private function foo($val){ return intval($val)+1; } public function test(){ $arr = array('a',2,'b',5,'c',7); //回调函数传递方式 $res = array_map(array($this, 'foo'), $arr); return $res; } } $demo = new Demo; $result = $demo->test();
Method 4, class public static Method
class Demo { static public function foo($val){ return intval($val)+1; } } $arr = array('a',2,'b',5,'c',7); //回调函数传递方式 以下两种方式都可以 $res = array_map('Demo::foo', $arr); //$res = array_map(array('Demo', 'foo'), $arr);
Method 5, class private static method
class Demo { static private function foo($val){ return intval($val)+1; } static public function test(){ $arr = array('a',2,'b',5,'c',7); //回调函数传递方式 这里可以使用两种传递方式 $res = array_map(array('self', 'foo'), $arr); //$res = array_map('self::foo', $arr); //$res = array_map(array('Demo', 'foo'), $arr); //$res = array_map('Demo::foo', $arr); return $res; } } $result = Demo::test();
Method 6, anonymous function
$foo = function($val){ return intval($val)+1; }; $arr = array('a',2,'b',5,'c',7); //回调函数传递方式 $res = array_map($foo, $arr);
Related recommendations:
PHP callback function and Detailed explanation of the use of anonymous functions
Completely master js callback functions
Parsing of PHP callback functions
The above is the detailed content of PHP callback function type transfer method. For more information, please follow other related articles on the PHP Chinese website!