-
Notifications
You must be signed in to change notification settings - Fork 0
Open
Labels
Description
Sniff basics | - |
---|---|
Fixable for PHP: | 5.3+ |
Sniff type: | Modernize |
Fixer type: | Risky |
Short description
PHP 5.3 introduced anonymous functions - also called closures - for on the fly function creation. Previously this was only possible using a call to create_function()
.
Use of create_function()
has been deprecated as of PHP 7.2 and is slated to be removed in PHP 8.0.
Related PHPCompatibility sniff(s):
NewClosure
DeprecatedFunctions
PHP manual references:
- http://php.net/manual/en/functions.anonymous.php
- http://php.net/manual/en/function.create-function.php
Example code:
Detect the following code pattern(s):
$newfunc = create_function('$a,$b', 'return "ln($a) + ln($b) = " . log($a * $b);');
$garr = array(
create_function('$b,$a', 'if (strncmp($a, $b, 3) == 0) return "** \"$a\" '.
'and \"$b\"\n** Look the same to me! (looking at the first 3 chars)";'),
create_function('$a,$b', '; return "CRCs: " . crc32($a) . ", ".crc32($b);'),
create_function('$a,$b', '; return "similar(a,b) = " . similar_text($a, $b, &$p) . "($p%)";')
);
array_walk($av, create_function('&$v,$k', '$v = $v . "mango";'));
And fix these to:
$newfunc = function($a,$b) { return "ln($a) + ln($b) = " . log($a * $b); };
$garr = array(
function($b,$a) { if (strncmp($a, $b, 3) == 0) return "** \"$a\"
and \"$b\"\n** Look the same to me! (looking at the first 3 chars)";},
function($a,$b) {; return "CRCs: " . crc32($a) . ", ".crc32($b);},
function($a,$b) {; return "similar(a,b) = " . similar_text($a, $b, &$p) . "($p%)";}
);
array_walk($av, function(&$v,$k) { $v = $v . "mango";});
Notes for implementation of the sniff:
- Beware of escaped quotes in the code passed to
create_function()
. - Beware of single versus double quotes. Variables in a double quoted string may expand to additional code.
- Beware of
$code
being concatenated or being passed a variable. - If the original function call was single line, but contained multiple statements in the
$code
parameter, it should probably be turned into a multi-line function layout. The indentation should be left to the code-style sniffs of the code base and are not the concern of this library. - Beware of a potential
@
silence operator before the call tocreate_function()
and if found, it needs to be removed. - This sniff will need to be extensively tested!
For code which still has to support PHP < 5.3 as well as PHP 7.2+, the sniff could add the @
silence operator to the create_function()
call to prevent the deprecated function notice from being thrown.
Pharaoh2k and Eslam2010