Home Backend Development PHP Tutorial Analysis of PHP callback function

Analysis of PHP callback function

Dec 22, 2017 am 10:41 AM
php function callback

People who are familiar with node development must be familiar with callback functions, but they are not commonly used in PHP. In fact, PHP also supports callback functions. Today we will explain in detail the use of callback functions and anonymous functions in PHP.

Callback function

Callback function: Callback (i.e. call then back
will return to the main function after being called by the main function), which refers to a function that is passed to other codes through function parameters. A reference to a block of executable code.

The popular explanation is to pass the function as a parameter into another function for use; there are many functions in PHP that "require parameters as functions", such as array_map, usort, call_user_func_array, etc., they execute the passed in function and then returns the result directly to the main function. The advantage is that functions are convenient to use as values, and the code is concise and readable.

Anonymous function:

Anonymous function, as the name suggests, is a function without a determined function name. PHP treats anonymous functions and closures as the same concept (anonymous functions are also called closure function). Its usage, of course, can only be used as a variable.

There are four ways to assign a function to a variable in PHP:

We often use: the function is defined externally/or built-in in PHP, and the function name is directly used as a string Parameters are passed in. Note: If it is a class static function, it is passed in as CLASS::FUNC_NAME.

Use create_function($args, $func_code); to create a function and a function name will be returned.
$func_code is the code body, $args is the parameter string, separated by ',';

Direct assignment: $func_name = function($arg){statement};

Direct Use anonymous functions to define functions directly at parameters without assigning specific variable values;

The first method is commonly used and will not be mentioned further; the second method is similar to the use of the eval() method, It is also officially listed as a deprecated method by PHP, and its definition method is too unintuitive. I have not used it in other places except for testing, and I will not mention it. Here we focus on the third and fourth usages;

The functions created by the latter two are called anonymous functions, that is, closure functions. The functions created by the third assignment method are very flexible. , can be referenced through variables. You can use is_callable($func_name) to test whether this function can be called, or you can call it directly through $func_name($var); the function created in the fourth way is more similar to the callback function in JS and does not require variable assignment. , used directly;

Another special introduction is the use keyword, which can be used to reference variables in the parent scope when defining a function; the usage is function($arg) use($outside_arg) { function_statement}. Among them, $outside_arg is a variable in the parent scope and can be used in function_statement.

This usage is used in the callback function "the number of parameter values ​​is determined". For example, usort requires that the parameter value of $callback be two items, but what if we need to introduce other parameters to affect the sorting? Using the use() keyword, it is very convenient to introduce a new variable into $callback for internal use.


array_map/array_filter/array_walk:

Put these three functions together because the execution logic of these three functions is similar, similar to The following code:

$result = [];
foreach($vars as $key=>$val){
        $item = callback();
        $result[] = $item;
}
return $result;
array_walk($vars, $callback)
Copy after login

The callback should be as follows:

$callback = function(&$val, $key[, $arg]){    
   doSomething($val);
}
Copy after login

array_walk returns whether the execution is successful, which is a Boolean value. Adding a reference symbol to $value can change the $value value within the function to achieve the effect of changing the $vars array. Since its $callback requires two parameters, array_walk cannot pass in $callbacks such as strtolower/array_filter. If you want to achieve similar functions, you can use array_map() to be discussed next.

array_walk_recursive($arr, $callback);

The return value and execution mechanism are similar to array_walk;

The callback is the same as array_walk, the difference is that if $val is an array , the function will recursively process $val downward; it should be noted that in this case, $val is the $key of the array and will be ignored.

array_filter($vars, $callback, $flag);

The $callback is similar to:

$callback = function($var){
   return true or false;         
}
Copy after login

array_filter will filter out items that return false when $callback is executed , array_filter returns the array after filtering is completed.

The third parameter $flag determines the value of its callback parameter $var, but this may be a feature of higher versions of PHP. My PHP5.5.3 does not support it. You can test it yourself. By default, the value of each item in the array is passed in. When the flag is ARRAY_FILTER_USE_KEY, the key of each item in the array is passed in, and ARRAY_FILTER_USE_BOTH is passed in the key and value;

array_map($callback, &$var_as [,$var_bs...] );

The $callback is similar to:

$callback = function($var_a[, $var_b...]){
     doSomething($var_a, $var_b);
}
Copy after login

Returns the array of $var_as processed by callback (the original array will be changed); if there are multiple arrays, the two arrays will be in the same order The items are passed in for processing, and the number of executions is the maximum number of items in the parameter array;


usort/array_reduce

Put these two functions together , because their execution mechanisms are somewhat special.

usort(&$vars, $callback)

$callback should be as follows:

callback = function($left, $right){
    $res = compare($left, $right);
    return $res;
}
Copy after login

usort returns whether the execution is successful or not, bool value. The user-defined method compares $left and $right, where $left and $right are any two items in $vars;

$left > Returns a positive integer when $left < $right Returns a negative integer, returns 0 when $left = $right;

$vars中的元素会被取出会被由小到大升序排序。 想实现降序排列,将$callback的返回值反一下就行了。

array_reduce($vars ,$callable [, mixed $initial = NULL])

$callback应该如下:

$callback = function($initial, $var){
    $initial = calculate($initail, $var);
    return $initial;
}
Copy after login

初始值$initial默认为null,返回经过迭代后的initial;一定要将$initial返回,这样才能不停地改变$initial的值,实现迭代的效果。

这里顺便说一下map和reduce的不同:

map:将数组中的成员遍历处理,每次返回处理后的一个值,最后结果值为所有处理后值组成的多项数组;

reduce:遍历数组成员,每次使用数组成员结合初始值处理,并将初始值返回,即使用上一次执行的结果,配合下一次的输入继续产生结果,结果值为一项;


call_user_func/call_user_func_array

call_user_func[_array]($callback, $param)

$callback形如:

$callback = function($param){
    $result = statement(); 
    return $result;
}
Copy after login

返回值多种,具体看$callback。

可用此函数实现PHP的事件机制,其实并不高深,在判断条件达成,或程序执行到某一步后 call_user_func()就OK了。这个我在之前的博客中也有介绍到:搭建自己的PHP框架心得(二)


总结

其实以上$callback不用单独定义并使用变量引用,使用上面说过的第四种函数定义方式,直接在函数内定义,使用‘完全’匿名函数就行了。 如:

usort($records, function mySortFunc($arg) use ($order){
      func_statement;
});
Copy after login

是不是逼格满满呢?

相关阅读:

php的闭包(Closure)匿名函数初探

详解PHP匿名函数与注意事项

PHP匿名函数和use子句用法实例,匿名use子句实例_PHP教程

The above is the detailed content of Analysis of PHP callback function. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles