Concept
How can functions be assigned to variables and used as callbacks in PHP?
ComputerScienceOne / Generalized Rounding
"40.1.6. Function Pointers Functions are just pieces of code that reside somewhere in memory just as variables do. Since we can pass variables by reference, it also makes sense that we would do the same with functions. In PHP, functions are first-class citizens 2 meaning that you can assign a function to a variable just as you would a numeric value. For example, you can do the following. 1 $func = swapByRef; 2 3 $func($x, $y); In the example above, we assigned the function swapByRef() to the variable $func by using its identifier. The variable essentially holds a reference to the swapByRef() function. Since it refers to a function, we can also invoke the function using the variable as in the last line. This allows you to treat functions as callbacks to other functions. We will revisit this concept in Chapter 47. 2 Some would use a much more restrictive definition of first-class and would not consider them first-class citizens in this sense"
Related Ideas
- How can functions be assigned to variables and invoked as callbacks?ComputerScienceOne · Function Pointers
- How do callbacks make C functions more generic?ComputerScienceOne · Function Pointers
- What is a function pointer and how is it declared?ComputerScienceOne · Function Pointers
- How can function pointers point to and call different functions?ComputerScienceOne · Generalized Rounding
- What programming structures and memory concepts support reusable code?ComputerScienceOne · Glossary
- How does PHP pass arguments by reference?ComputerScienceOne · Passing By Reference
- How do you call a PHP function with values or variables?ComputerScienceOne · Organizing Functions
- How do you declare functions and specify their return values in PHP?ComputerScienceOne · Declaring Functions