what is php closure

(*-*)浩
Release: 2023-02-26 06:54:01
Original
5114 people have browsed it

php closure is to temporarily create a function without a name, which is often used as a callback function. In layman's terms: child functions can use local variables in the parent function. This behavior is called closure.

what is php closure

When mentioning closures, you have to think of anonymous functions, also called closure functions (closures). It seems that PHP closure implementation mainly relies on it. . Declare an anonymous function like this:

The code is as follows:(Recommended learning: PHP video tutorial)

$func = function() {
}; //带结束符
Copy after login

As you can see, the anonymous function is because Without a name, you need to return it to a variable if you want to use it. Anonymous functions can also declare parameters like ordinary functions, and the calling method is also the same:

The code is as follows:

$func = function( $param ) {
echo $param;
};
$func( 'some string' );
//输出:
//some string
Copy after login

Implement closure

Pass anonymous functions as parameters in ordinary functions, and they can also be returned. This implements a simple closure.

//在函数里定义一个匿名函数,并且调用它
function printStr() {
    $func = function( $str ) {
        echo $str;
    };
    $func( 'some string' );
}
printStr();
输出: some string
Copy after login

The above is the detailed content of what is php closure. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template