Why does php need anonymous functions?

(*-*)浩
Release: 2023-02-24 06:12:01
Original
3084 people have browsed it

Anonymous functions, also called closures, allow the temporary creation of a function without a specified name. The value most commonly used as a callback function argument. Of course, there are other applications as well.

Why does php need anonymous functions?

Anonymous functions are currently implemented through the Closure class.

Anonymous function example(Recommended learning: PHP programming from entry to proficiency)

<?php
echo preg_replace_callback(&#39;~-([a-z])~&#39;, function ($match) {
    return strtoupper($match[1]);
}, &#39;hello-world&#39;);
// 输出 helloWorld
?>
Copy after login

Closure functions can also be used as the value of variables . PHP will automatically convert this expression into an object instance of the built-in class Closure. The method of assigning a closure object to a variable is the same as the syntax of ordinary variable assignment, and a semicolon must be added at the end:

Anonymous function variable assignment example

<?php
$greet = function($name)
{
    printf("Hello %s\r\n", $name);
};

$greet(&#39;World&#39;);
$greet(&#39;PHP&#39;);
?>
Copy after login

Closures can inherit variables from the parent scope. Any such variables should be passed in using the use language construct. Starting from PHP 7.1, such variables cannot be passed in: superglobals, $this or have the same name as parameters.

The above is the detailed content of Why does php need anonymous functions?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!