In this tutorial we will learn about the closure function in php. Here we will see simple closure using an anonymous function.
Example 1:
// Create a user
$user = "xyz";
// Create a Closure
$invoke = function() use($user) {
echo "Hello $user";
};
// Greet the user
$invoke(); // Returns "Hello xyz"
Example 2:
// A simple example of a closure
function invoke() {
$message = "Hello";
return ( function( $name ) use ( $message ) {
return ( "$message, $name!" );
} );
};
$invoke = invoke();
echo $invoke( "abcd" ); // Displays "Hello, abcd!"
As we can see in the above examples, the Closure is able to access the $user/$message variable because it was declared in the use clause of the Closure function definition.
If we alter the $user/$message variable within the Closure, it will not effect the original variable. If we want to update the original variable, we need to prepend an ampersand (& ) to the $user/$message variable as a reference which will updated the original value of $user/$message.
Example3:
// Create a user
$user = "xyz";
// Create a Closure
$invoke = function() use(&$user) {
echo "Hello $user";
};
$user = "abcd";
// Invoke the user
$invoke(); // Returns "Hello abcd"
Link to create anonymous function
0 Comment(s)