PHP Anonymous Functions with Example Programs

In this section, you will learn more about useful knowledge in the field of PHP programming. This will deepen your intellect and broadens your skills as it presents the PHP anonymous functions with example programs.

Now let us clarify…

What are PHP anonymous functions?

PHP is known as a leading tool for web development as it is a general-purpose scripting language. Along with this fame, the language also possesses anonymous functions which can help you in various ways.

Furthermore, PHP anonymous functions are also called closure or lambda functions. This allows programmers to create and use functions even that are not specified in the language.

The “anonymous” functions were useful for callable parameters and many other uses. To implement them, you can apply the closure class to your program.

Let us familiarize the correct syntax of anonymous functions and try to implement them in the examples below.

PHP anonymous functions – Syntax

$var=function ($arg1, $arg2) { return $val; };

Here are the attributes of a PHP anonymous function:

  • There is no function name present between the function keyword and the opening parentheses.
  • Its function definition is followed by a semicolon since anonymous function definitions are expressions.
  • The assigned variable is a function, which is then called using the variable’s name.
  • It is known as a callback when supplied to another function that can then call it later.
  • It gets it back from a function outside of it so that it can use the variables of the function outside of it. 

Anonymous Function Example Program

Now let us have our first example using the PHP anonymous function. However, please bear in mind that the word anonymous function is not known in the PHP language.

Example Program

<?php
echo preg_replace_callback('~-([a-z])~', function ($abc) {
    return strtoupper($abc[1]);
}, 'Welcome to ITSourceCode!');
?>

Output

Welcome to ITSourceCode!

Code Explanation

In this example, we directly use the “anonymous function” without assigning any name for that particular function. Basically, the implementation of a function is based on the assigned operation within that function.

Therefore, this first example shows you how to use the PHP anonymous function without assigning a specific name to that function.

However, you may assign a name that you desire to specify the function that you want at your convenience.

Example Program for Passing an Anonymous Function to Another Function

Let us have another example where we can pass the PHP anonymous function to another. This concept will help us use the operation assigned to a specific function and pass this operation to another function.

Example Program

<?php 
function times_two($a)
{
	return $a * 2;
}

$sample = array(10, 20, 30);
print_r(array_map('times_two', $sample));

?>

Output

Array ( [0] => 20 [1] => 40 [2] => 60 )

Code Explanation

As seen in this example, we assign an operation in the function times_two which is to use the variable $a and return $a * 2. The $a * 2 is the assigned operation in the function times_two.

The operation of the function is then passed into another function applied to the next argument. To enable this situation, we call the times_two function as a string to pass the operation in the next argument.

As a result, the program displays the output of Array ( [0] => 20 [1] => 40 [2] => 60 ). This indicates that the operation of the function works in another argument.

Example Program to Return an Anonymous Function from a Function

From passing the function to another, let us now test to return the PHP anonymous function from a function. Take a look at the example below,

Example Program

<?php

function multiply($a)
{
	return function ($b) use ($a) {
		return $a * $b;
	};
}

$double = multiply(2);
echo "The doubled value of 10 is " . $double(10) . ". <br/>";

$tripple = multiply(3);
echo "The trippled value of 10 is " .$tripple(10) . ".";
?>

Output

The doubled value of 10 is 20.
The trippled value of 10 is 30.

Code Explanation

In this example, you will see that we have a complex situation in which we try to return another function from another. So we use the function multiply ($a) to execute its operation to return the function $b using the element $a.

Now to execute the program, we have the two arguments applying the function multiply(). In the first argument, the value of $a is 2, and $b is 10. This means that we multiply the a and b to come up with our desired output.

This operation also goes the same in the second argument. Therefore the PHP anonymous function works efficiently in returning the operation from another element.

Scope of the Anonymous Function

In this section, you will be able to understand the scope of an anonymous function in PHP. See this example to have a clear implementation:

Program Example

<?php

$message = 'Welcome to ITSourceCode.';
$say = function () use ($message) {
	$message = 'Good day!';
	echo $message . "<br/>";
};

$say();
echo $message;
?>

Output

Good day!
Welcome to ITSourceCode.

Code Explanation

The example signifies that the scope of the PHP anonymous function includes constants, properties, and methods. This means that the anonymous function supports a lot of operations within its scope with the proper declaration.

Summary

In summary, the topic has now covered all the information you need to fully understand PHP anonymous function. The topic also stresses diverse uses of the function which opens a lot of opportunities for programmers.

Through PHP anonymous function, programmers are allowed to define the function with their desired operations. It also improves programmers’ experience and their exploration of new skills.

Leave a Comment