search
HomeBackend DevelopmentPHP TutorialDetailed explanation of the usage of php callback functions and anonymous functions

Detailed explanation of the usage of php callback functions and anonymous functions

Jun 26, 2017 pm 02:29 PM
phpfunctionAnonymoususageDetailed explanation

Callback functionandAnonymous function

Callback function and closure are no strangers in JS. JS can use them to complete the event mechanism and perform many complex tasks. operate. It is not commonly used in PHP. Today, let’s talk about callback functions and anonymous functions in PHP.

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

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, 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 functions in PHP). 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};

Use anonymous function directly , define the function directly at the parameter, without assigning specific variable values;

The first method is commonly used and will not be mentioned further; the second method is similar to the eval() method, and is also used by PHP The official method is not recommended, and its definition 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 relatively similar, similar to the following code :

$result = [];
foreach($vars as $key=>$val){
    $item = callback();
    $result[] = $item;
}
return $result;

The callback should be as follows:

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

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, but the difference is , 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;         
            }

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);
        }

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

把这两个函数放在一块,因为他们的执行机制都有些特殊。

usort(&$vars, $callback)

$callback应该如下:

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

usort返回执行成功与否,bool值。用户自定义方法 比较$left 和 $right,其中$left和$right是$vars中的任意两项;

$left > $right时返回 正整数, $left

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

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

$callback应该如下:

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

初始值$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;
    }

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

The above is the detailed content of Detailed explanation of the usage of php callback functions and anonymous functions. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment