Can a function be passed as a parameter to another function in PHP?
Yes, in PHP, you can pass a function as a parameter to another function. This is commonly done using anonymous functions or closures. By passing functions as parameters, you can create more flexible and reusable code.
// Function that takes another function as a parameter
function processFunction($callback) {
// Call the passed function
$result = $callback();
// Do something with the result
echo "Result: " . $result;
}
// Define a function to be passed
$myFunction = function() {
return "Hello, World!";
};
// Call the function and pass the defined function
processFunction($myFunction);
Keywords
Related Questions
- What are the advantages and disadvantages of using Template-Engine libraries like Twig or Plates in PHP development?
- What are some common pitfalls to avoid when working with time functions in PHP?
- How important is it to ensure that the specified temporary directory for session data storage actually exists in the server environment when working with PHP sessions?