There are two subtle but important differences between the above example and a regular function definition:
- There is no function name between the
function
keyword and the opening parenthesis ('('
). This tells PHP that you’re creating an anonymous function. - There is a semicolon after the function definition. This is because anonymous function definitions are expressions, whereas regular function definitions are code constructs.
While the above code is perfectly valid, it isn’t very useful. Since the anonymous function has no name, you can’t refer to it anywhere else in your code, so it can never be called!
However, since an anonymous function is an expression — much like a number or a string — you can do various handy things with it. For example, you can:
- Assign it to a variable, then call it later using the variable’s name. You can even store a bunch of different anonymous functions in a single array.
- Pass it to another function that can then call it later. This is known as a callback.
- Return it from within an outer function so that it can access the outer function’s variables. This is known as a closure.
You’ll explore these three techniques in the rest of this tutorial.
No comments:
Post a Comment