Junior
What are arrow functions and anonymous functions in PHP?
sobes.tech AI
Answer from AI
Arrow functions are syntactic sugar for anonymous functions introduced in PHP 7.4. They provide a more concise way to write simple lambda functions.
-
Anonymous functions (closures):
- Can include more than one line of code and contain complex logic.
- Use the
usekeyword to import variables from the parent scope. - More flexible, suitable for complex tasks.
-
Arrow functions:
- Contain only one expression, which is returned implicitly.
- Have automatic access to variables from the parent scope (do not require
use). - Designed for simple, one-line operations.
Here are examples:
<?php
// Anonymous function
$greet = function ($name) {
return "Hello, " . $name;
};
echo $greet('World') . "\n";
// Anonymous function with use
$message = 'Hello';
$greetWithMsg = function ($name) use ($message) {
return $message . ", " . $name;
};
echo $greetWithMsg('Friend') . "\n";
<?php
// Arrow function
$greetArrow = fn ($name) => "Hello, " . $name;
echo $greetArrow('World') . "\n";
// Arrow function with automatic access to parent scope
$messageArrow = 'Hello';
$greetArrowWithMsg = fn ($name) => $messageArrow . ", " . $name;
echo $greetArrowWithMsg('Friend') . "\n";
Differences in restrictions:
| Capability | Anonymous function | Arrow function |
|---|---|---|
| Multiline code | Yes | No |
return keyword |
Yes (mandatory) | No (implicit) |
use keyword |
Yes (for import) | No (automatic) |
| Complex logic | Yes | No |
The choice between them depends on the complexity of the task and preferences in syntax. For simple actions, it is more convenient to use arrow functions due to their brevity.