PHPer 高手之路
  • Introduction
  • First Chapter
  • 基础
    • 数据类型和常量
    • 字符串
      • 字符编码
      • 字符编码相关编程
    • 引用变量
    • 运算符与错误控制符@
    • 流程控制与条件判断
      • foreach遍历中的引用
    • 函数
    • 文件及目录处理
  • PHP 数组
    • 基础
    • PHP数组操作
    • 输入流 php://input
    • PHP数组的内部实现
    • PHP数组和数据结构
    • 示例技巧
  • PHP文件编程
    • 文件系统
    • 基础
    • 实例技巧
    • PHP中XML处理
    • PHP中JSON处理
    • PHP中CSV处理
    • 大文件上传
  • 正则表达式
    • 基础
    • 正则的引擎
    • 表达式的优化
    • PHP中正则的使用
  • PHP 编码技巧
    • PHP编码习惯
    • PHP语法糖
    • PHP代码优化
    • PHP重点新特性
    • PHP编码规范
  • PHP选项和运行原理
    • PHP SAPI
    • PHP运行模式及安装方式
    • 附录:进程和线程的Q解
    • Apache下的MPM模式
    • Apache 与 Nginx
    • PHP的运行机制及原理
    • PHP垃圾回收机制
    • PHP配置选项
  • PHP安全
    • 跨站脚本攻击(XSS )
    • 跨站请求伪造(CRSF)
  • PHP 高级特性
    • 异常处理(Exceptions)
    • 代码复用(Trait)
    • 预定义接口(Predefined Interfaces)
    • 魔术方法(Magic Methods)
    • 回调函数、匿名函数&闭包
    • 命名空间(Namespaces)
    • 自动加载(Autoload)
    • 反射(Reflection)
    • 魔术常量(Magic constants)
    • 综合实例
  • 附录:关键词
  • 附录:资料
  • 代码的版本控制
    • SVN
    • Git
      • 疑难杂症
  • Linux
    • Linux原理与基础
    • 常见命令
    • Shell 编程
    • awk 与 sed
    • 命令笔记
  • HTTP 协议
    • 请求方法与返回状态码
    • Cookie、Session 的原理
  • MySQL
    • MySQL表存储引擎
  • 标准PHP库(SPL)
    • 数据结构
      • SplPriorityQueue - 优先队列
      • SplQueue - 队列
      • SplStack - 栈的功能
    • 接口
      • Countable - count统计接口
  • 附录:ElasticSearch
  • PHP数据结构
  • 附录:Rabbitmq
  • 附录:guzzle
  • JavaScript
    • 附录:资料
  • 疑难杂症
Powered by GitBook
On this page
  • 回调 (callbacks)
  • 匿名函数和闭包(Anonymous functions & Closures)
  • 回调函数相关的函数:

Was this helpful?

  1. PHP 高级特性

回调函数、匿名函数&闭包

回调 (callbacks)

比如usort(array &$array , callable $compareFunc)

第一个参数为数组,第二个参数是回调方法

使用方法:

usort($arr, 'mySortFunc');
//回调方法在对象中
usort($arr, array($objectName, 'mySortFunc'));
//回调方法在类的静态方法里
usort($arr, array('ClassName', 'mySortFunc'));
usort($arr, array('ClassName::mySortFunc'));
//通过子类调用父类中的方法(很少用)
usort($arr, array('Child', 'parent::mySort'));

匿名函数方式

usort($arr, function($a, $b) {
return $b - $a;

匿名函数和闭包(Anonymous functions & Closures)

示例:

注意use关键是使用外部变量,相当于复制一份变量值,当掉后面改变变量值时,匿名函数内部的变量值不会发生改变

$string = "Hello World!\n";

$closure = function() use ($string) { 
    echo $string; 
};

$string = "Hello China\n";

$closure();

结果:

Hello World!

示例

函数返回的闭包

$string = "Hello China\n";

function getPrinter(&$string) {

    return function() use($string) {
        echo $string;
    };
}

$printer = getPrinter($string);

$string = "Hello Cat\n";

$printer();

结果:

Hello China

回调函数相关的函数:

<?php

 function test($str) {
    echo $str;
}


echo is_callable('test');
call_user_func('test', 'param1');
call_user_func_array('test', ['param1']);
Previous魔术方法(Magic Methods)Next命名空间(Namespaces)

Last updated 5 years ago

Was this helpful?

—检测参数是否为合法的可调用结构

—把第一个参数作为回调函数调用

—调用回调函数,并把一个数组参数作为回调函数的参数

is_callable
call_user_func
call_user_func_array