A closure function in PHP is an anonymous function nested in another function that can access the variables of the external function. The use keyword can be used to access external variables in the closure function, which can be applied in actual scenarios where discounts need to be applied to each element in the list.
Closure function in PHP function
A closure function is an anonymous function nested in another function. Variables of external functions can be accessed even if the external function has returned. Closure functions are very useful in PHP because they allow creating reusable blocks of code and maintaining access to the external environment.
Creating a Closure Function
To create a closure function in PHP, use the function
keyword, followed by an optional name and parameters List:
$closure = function($arg1, $arg2) { // 函数体 };
The variable scope rules in closure functions are as follows:
use
in the closure function. Useuse
keyword
use
keyword is used to introduce external variables into the closure function . For example:
function outerFunction($arg1) { $outerVar = '外部变量'; $closure = function() use ($arg1, $outerVar) { // 闭包函数可以访问 $arg1 和 $outerVar }; }
Practical Case
Suppose you need to create a function that applies a discount to each element in a list. To do this, you can create a closure function to calculate the discount amount:
function applyDiscount($list, $discountPercentage) { // 创建闭包函数来计算折扣 $discountClosure = function($item) use ($discountPercentage) { return $item - ($item * ($discountPercentage / 100)); }; // 将折扣闭包函数应用于列表中的每个元素 return array_map($discountClosure, $list); }
Full code:
function outerFunction($arg1) { $outerVar = '外部变量'; $closure = function() use ($arg1, $outerVar) { // 闭包函数可以访问 $arg1 和 $outerVar echo "arg1: $arg1<br>"; echo "outerVar: $outerVar<br>"; }; // 调用闭包函数 $closure(); } applyDiscount([10, 20, 30], 10); // [9, 18, 27]
The above is the detailed content of How to create closure function of PHP function?. For more information, please follow other related articles on the PHP Chinese website!