0
0
PHPprogramming~5 mins

Anonymous function syntax in PHP - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is an anonymous function in PHP?
An anonymous function is a function without a name. It can be stored in a variable and used like any other function.
Click to reveal answer
beginner
How do you declare an anonymous function in PHP?
Use the function keyword without a name, followed by parentheses and curly braces. Example: $fn = function() { echo 'Hi'; };
Click to reveal answer
intermediate
How can you pass variables from the parent scope into an anonymous function?
Use the <code>use</code> keyword to import variables. Example: <code>$msg = 'Hello'; $fn = function() use ($msg) { echo $msg; };</code>
Click to reveal answer
beginner
Can anonymous functions in PHP be assigned to variables and called later?
Yes. You assign the anonymous function to a variable and call it using parentheses. Example: $fn = function() { echo 'Hi'; }; $fn();
Click to reveal answer
intermediate
What is a common use case for anonymous functions in PHP?
They are often used as callbacks, for example in array functions like array_map or usort, to define small pieces of code inline.
Click to reveal answer
How do you declare an anonymous function in PHP?
Afunction() { /* code */ }
Bdef function() { /* code */ }
Cfunction myFunc() { /* code */ }
Dlambda() => { /* code */ }
How do you pass a variable from outside into an anonymous function in PHP?
AUsing the global keyword
BBy declaring it inside the function
CYou cannot pass variables into anonymous functions
DUsing the use keyword
Which of these is a valid way to call an anonymous function stored in a variable $fn?
A$fn.call();
Bcall $fn();
C$fn();
Dcall_function($fn);
What is a common use of anonymous functions in PHP?
AWriting long scripts
BUsing as callbacks in functions like array_map
CDefining class methods
DReplacing all named functions
Can anonymous functions in PHP have parameters?
AYes, just like normal functions
BNo, they cannot have parameters
COnly one parameter is allowed
DParameters must be global variables
Explain how to create and use an anonymous function in PHP, including how to pass external variables into it.
Think about the function keyword without a name and the use keyword.
You got /4 concepts.
    Describe a practical example where anonymous functions are useful in PHP programming.
    Consider functions like array_map or usort.
    You got /4 concepts.