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 best practices for handling user input from a button click and sending it to a database in PHP?
- How can PHP beginners ensure the security of their encrypted document IDs when using base64_encode and serialize functions?
- What is the significance of the MIME type "text/plain" for .htaccess files in PHP?