1.2.154. Closure Could Be A Callback¶
Closure <https://www.php.net/manual/en/class.`closure.php>`_ and arrow function may be simplified to a callback. Callbacks are strings or arrays.
A simple closure <https://www.php.net/`closure>`_ that only returns arguments relayed to another function or method, could be reduced to a simpler expression.
Closure <https://www.php.net/manual/en/class.`closure.php>`_ may be simplified with a string, for functioncall, with an array for methodcalls and static methodcalls.
Performances : simplifying a closure <https://www.php.net/`closure>`_ tends to reduce the call time by 50%.
<?php
// Simple and faster call to strtoupper
$filtered = array_map('strtoupper', $array);
// Here the closure doesn't add any feature over strtoupper
$filtered = array_map(function ($x) { return strtoupper($x);}, $array);
// Methodcall example : no fix
$filtered = array_map(function ($x) { return $x->strtoupper() ;}, $array);
// Methodcall example : replace with array($y, 'strtoupper')
$filtered = array_map(function ($x) use ($y) { return $y->strtoupper($x) ;}, $array);
// Static methodcall example
$filtered = array_map(function ($x) { return $x::strtoupper() ;}, $array);
// Static methodcall example : replace with array('A', 'strtoupper')
$filtered = array_map(function ($x) { return A::strtoupper($x) ;}, $array);
?>
See also Closure class and Callbacks / Callables.
1.2.154.1. Connex PHP features¶
1.2.154.1.1. Suggestions¶
Replace the closure by a string, with the name of the called function
Replace the closure by an array, with the name of the called method and the object as first element
1.2.154.1.2. Specs¶
Short name |
Functions/Closure2String |
Rulesets |
|
Exakat since |
1.4.3 |
PHP Version |
All |
Severity |
Minor |
Time To Fix |
Quick (30 mins) |
Precision |
Very high |
Examples |
|
Available in |