Anonymous Function
2 min readSep 23, 2024
What is anonymous function
An anonymous function is a function that has no name. This function is often used to provide a callback or temporary function that can be defined directly in another context, such as when using another function.
The purpose of creating anonymous functions
Anonymous functions, or anonymous functions, are created to provide flexibility and ease in software development. Here are some of their purposes:
- Code Conciseness: Anonymous functions allow for writing more concise code without the need to define functions by name.
- Function As Argument: Can be used as an argument in other functions, as in functional programming, to increase modularity.
- Saving Context: Antonym functions are often used to store context (closure), so that variables can be accessed from their environment without having to define the function separately.
- Temporary Use: Useful for functions that are only needed once, so there is no need to pollute the namespace with unused function definitions.
- Ease of Callback:Often used in callbacks, such as in event processing, to provide an immediate response to an action.
When to Use anonymous functions
- Callback in function
When you need a temporary function as an argument to another function (misalnya, dalamarray_map
,array_filter
, atauusort
)
$result = array_map(function($num) {
return $num * 2;
}, $numbers);
- Closure
We need to access variables from the outer scope, synonymous functions withuse
allows you to create closures that preserve context.
$factor = 3;
$multiply = function($num) use ($factor) {
return $num * $factor;
};
- Temporary Function: If you need a function for single use, using an anonymous function helps keep the namespace clean, without having to define a separate function.
$result = array_filter($array, function($value) {
return $value > 10;
});
Example Implementation
public function approve(array $data, int $id): bool
{
$data['keterangan'] = null;
return $this->processApproval($data, $id, fn($level, $status) => StatusSuratEnum::approveNextStatus($level, $status));
}
protected function processApproval(array $data, int $id, callable $statusMethod, bool $generate = true): bool
{
// your logic magic
$data['status'] = $statusMethod($result->level_surat, $result->status);
return $this->update($data, $id);
}