Assigning anonymous functions to variables
When you define an anonymous function, you can then store it in a variable, just like any other value. Here’s an example:
// Assign an anonymous function to a variable $makeGreeting = function( $name, $timeOfDay ) { return ( "Good $timeOfDay, $name!" ); };
Once you’ve done that, you can call the function using the variable’s name, just like you call a regular function:
// Call the anonymous function echo $makeGreeting( "Fred", "morning" ) . "<br>"; echo $makeGreeting( "Mary", "afternoon" ) . "<br>";
This produces the output:
Good morning, Fred! Good afternoon, Mary!
You can even store several functions inside an array, like this:
// Store 3 anonymous functions in an array $luckyDip = array( function() { echo "You got a bag of toffees!"; }, function() { echo "You got a toy car!"; }, function() { echo "You got some balloons!"; } );
Once you’ve done that, your code can decide which function to call at runtime. For example, it could call a function at random:
// Call a random function $choice = rand( 0, 2 ); $luckyDip[$choice]();
No comments:
Post a Comment