How to Declare And Call Anonymous Function in PHP?

In PHP we can actually declare a function without any name. That is why it is called anonymous function. We can assign it to any variable and then call later whenever we need it.

$hi = function ($name){
	echo 'hi '.$name;
};

echo $hi('Alexander');
echo $hi('Hugh');

Another good example, could be making a function which returns 2 power of some number.

$powerOf2 = function ( $x ) {
	return pow( 2, $x );
};
echo "2^" . 4 . " = " . $powerOf2( 4 );
echo "2^" . 5 . " = " . $powerOf2( 5 );
echo "2^" . 6 . " = " . $powerOf2( 6 );

I personally used this concept more often in JavaScript rather in PHP but may be we are using it without knowing. For example, here is the code to sort an array.

function asc_number_sort( $x, $y ) {
	if ( $x['month'] > $y['month'] ) {
		return true;
	}
	else if( $x['month'] < $y['month'] ){
		return false;
	}
	else{
		return 0;
	}
}

usort( $array, 'asc_number_sort' );

But we can use pass whole function as second parameter to usort() function. Here is how it will be done.

usort( $array, function ( $x, $y ) {
	if ( $x['month'] > $y['month'] ) {
		return true;
	} else if ( $x['month'] < $y['month'] ) {
		return false;
	} else {
		return 0;
	}
});

 

Only problem with using anonymous function is it may introduce a lot of parse errors. That is why we declare it separately.