Home > Backend Development > PHP Problem > What can PHP anonymous functions be used for?

What can PHP anonymous functions be used for?

青灯夜游
Release: 2023-02-23 06:46:01
Original
3698 people have browsed it

What can PHP anonymous functions be used for?

Anonymous functions, also called closures, allow the temporary creation of a function without a specified name.

Benefits of anonymous functions

1. Non-anonymous functions create function objects and scope objects when they are defined. If they are not called in the future, they also take up space

2. Anonymous functions will only create function objects and scope objects when they are called. Release immediately after calling to save memory.

Use of anonymous functions in php

1. Use it as a callback function

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

2. Assign a variable value

<?php
$greet = function($name)
{
    printf("Hello %s\r\n", $name);
};
$greet(&#39;World&#39;);
$greet(&#39;PHP&#39;);
Copy after login

Output :

What can PHP anonymous functions be used for?

3. Inherit variables from the parent scope

<?php
$message = &#39;hello&#39;;
// 没有 "use"
$example = function () {
    var_dump($message);
};
echo $example();
// 继承 $message
$example = function () use ($message) {
    var_dump($message);
};
echo $example();
Copy after login

Output:

What can PHP anonymous functions be used for?

The above is the detailed content of What can PHP anonymous functions be used for?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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