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

## 回调 (callbacks)

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

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

使用方法:

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

匿名函数方式

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

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

示例:

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

```php
$string = "Hello World!\n";

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

$string = "Hello China\n";

$closure();
```

结果:

```
Hello World!
```

示例

函数返回的闭包

```php
$string = "Hello China\n";

function getPrinter(&$string) {

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

$printer = getPrinter($string);

$string = "Hello Cat\n";

$printer();
```

结果:

```
Hello China
```

### 回调函数相关的函数：

```php
<?php

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


echo is_callable('test');
call_user_func('test', 'param1');
call_user_func_array('test', ['param1']);
```

[is\_callable](http://php.net/manual/zh/function.is-callable.php)—检测参数是否为合法的可调用结构

[call\_user\_func](http://php.net/manual/zh/function.call-user-func.php)—把第一个参数作为回调函数调用

[call\_user\_func\_array](http://php.net/manual/zh/function.call-user-func-array.php)—调用回调函数，并把一个数组参数作为回调函数的参数


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://phper.shujuwajue.com/php-gao-ji-te-xing/hui-diao-han-shu-3001-ni-ming-han-657026-bi-bao.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
