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

What can PHP anonymous functions be used for?

青灯夜游
青灯夜游Original
2019-06-06 17:26:093690browse

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

2. Assign a variable value

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

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

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!

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
Previous article:What language is php?Next article:What language is php?

Related articles

See more