21xrx.com
2024-03-29 14:23:47 Friday
登录
文章检索 我的文章 写文章
PHP回调函数
2021-07-22 18:13:01 深夜i     --     --
P H P


回调函数

回调函数(通常称为“回调”)是作为参数传递给函数。

任何现有函数都可以用作回调函数。 使用函数作为回调 函数,传递包含函数名称的字符串作为参数:

将回调传递给PHP的array_map()函数以计算长度 数组中的每个字符串:

<?php
function my_callback($item) {
  return strlen($item);
}

$strings = ["apple", "orange", "banana", "coconut"];
$lengths = array_map("my_callback", $strings);
print_r($lengths);
?>

从版本7开始,PHP可以将匿名函数传递为回调函数:

使用匿名函数作为PHP的Array_Map()函数的回调:

<?php
$strings = ["apple", "orange", "banana", "coconut"];
$lengths = array_map( function($item) { return strlen($item); } , $strings);
print_r($lengths);
?>

用户定义的函数中的回调

用户定义的函数和方法也可以采用回调函数。 要在用户定义的函数或方法内使用回调函数, 通过向变量添加括号并将参数添加为正常来调用它 :

从用户定义的函数运行回调:
 

<?php
function exclaim($str) {
  return $str . "! ";
}

function ask($str) {
  return $str . "? ";
}

function printFormatted($str, $format) {
  // Calling the $format callback function
  echo $format($str);
}

// Pass "exclaim" and "ask" as callback functions to printFormatted()
printFormatted("Hello world", "exclaim");
printFormatted("Hello world", "ask");
?>


 

  
  
下一篇: PHP和JSON.

评论区

{{item['qq_nickname']}}
()
回复
回复