PHP anonymous functions

srdotlibre(40)
Published in
#php
Words
113
Reading
1 min
6y
Listen to this post
~1 min

An anonymous function, as its name implies, is nothing more than a function that has no name and that can be used as a callback allowing greater elegance and readability of source code, it is also possible to assign an anonymous function to a variable as were another data PHP type. PHP internally converts this variable in an instance of the Closure class.

Examples

  1. Let's have the following array and want to sort them using uasort
<?php
$array = array(
    'a' => 4, 
    'b' => 8, 
    'c' => -1, 
    'd' => -9, 
    'e' => 2, 
    'f' => 5, 
    'g' => 3, 
    'h' => -4
);

Before php-5.3.0 would have something like:

<?php
function compare($val1, $val2) 
{
    return $val1 == $val2 ? 0 : ($val1 < $val2 ? -1 : 1);
}

$array = array(
    'a' => 4, 
    'b' => 8, 
    'c' => -1, 
    'd' => -9, 
    'e' => 2, 
    'f' => 5, 
    'g' => 3, 
    'h' => -4
);

uasort($array, 'compare');

print_r($array);

// Result
//Array
//(
//  [d] = -9
//  [h] = -4
//  [c] = -1
//  [e] = 2
//  [g] = 3
//  [a] = 4
//  [f] = 5
//  [b] = 8
//)

As of PHP 5.3.0 using anonymous functions

<?php
$array = array(
    'a' => 4, 
    'b' => 8, 
    'c' => -1, 
    'd' => -9, 
    'e' => 2, 
    'f' => 5, 
    'g' => 3, 
    'h' => -4
);

uasort($array, function ($val1, $val2) {
    return $val1 == $val2 ? 0 : ($val1 < $val2 ? -1 : 1);
});

print_r($array);

// Result
//Array
//(
//  [d] = -9
//  [h] = -4
//  [c] = -1
//  [e] = 2
//  [g] = 3
//  [a] = 4
//  [f] = 5
//  [b] = 8
//)

Both examples produce the same result, but the second case allows a better organization and readability in source code.


Via LibreByte


PHP anonymous functions | Ecency