Bifalgorithm post · Computer science one · Function Pointers

How can functions be assigned to variables and invoked as callbacks?

How can functions be assigned to variables and invoked as callbacks? (Computer science one · Function Pointers) — "Functions are just pieces of code that resid…

Ideas in this flowchart

  • Functions can be treated as references and values in PHP.
  • Functions reside somewhere in memory, just as variables do.
  • Because variables can be passed by reference, functions can be handled similarly.
  • PHP functions are first-class citizens.
  • A function can be assigned to a variable using its identifier.
  • The assigned variable holds a reference to the function.
  • The function can be invoked through the variable.
  • This allows functions to serve as callbacks to other functions.
  • Example: $func = swapByRef; and $func($x, $y);
  • The callback concept is revisited in Chapter 47.
Feed/

How can functions be assigned to variables and invoked as callbacks?

No cover

Channel

Computer science one

1 page

"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, meaning that you can assign a function to a variable just as you would a numeric value. For example, you can do the following.\n\n$func = swapByRef;\n\n$func($x, $y);\n\nIn 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."

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.