Home >Backend Development >PHP Tutorial >How to use PHP inline functions?
PHP inline functions are anonymous functions that can be created through the fn() keyword and are used for one-time operations or to encapsulate complex logic. They can be passed as parameters, act as closures to access external variables, and are conveniently used in practical scenarios such as logging.
How to use PHP inline functions
PHP inline functions are anonymous functions, you can usefn()
Keyword creation. They are often used to perform one-time operations or to encapsulate complex logic in concise expressions.
Syntax
$function = fn(parameter_list) => expression;
Parameter passing
Inline functions can be passed as parameters to other functions. For example, here is an inline function that uses the built-in array_map()
function:
$numbers = [1, 2, 3, 4, 5]; $squaredNumbers = array_map( fn($n) => $n * $n, $numbers ); print_r($squaredNumbers); // 输出 [1, 4, 9, 16, 25]
Closure
Inline functions can access external variables , making it a closure. For example, here is a function that uses closures to track values:
$counter = 0; $incrementCounter = fn() => ++$counter; echo $incrementCounter(); // 输出 1 echo $incrementCounter(); // 输出 2
Practical example: logging
Inline functions can be very useful in logging. For example, here is a custom function that uses inline functions to log error messages:
function logError(string $message) { file_put_contents('errors.log', fn() => $message . "\n", FILE_APPEND); } logError('数据库连接失败');
Advantages
The main advantages of using PHP inline functions include:
The above is the detailed content of How to use PHP inline functions?. For more information, please follow other related articles on the PHP Chinese website!