Marcel Ang Marcel Ang - 2 years ago 73
PHP Question

PHP function as parameter of another function

In PHP can we do this?

function foo($c) {

echo 'done';

foo(function() {
echo 'test'

Such that the output will be:


This was my real problem :

function create_transaction($obj, $func, $errorMsg)
try {


} catch(Exception $e) {
throw new exception($errorMsg . ' ---> ' . $e);

So i can call this function of create_transaction like this :

create_transaction($obj, function() {
echo 'test';

// this should be a database CRUD process
// to make it simple, i just put echo.
}, 'error');

create_transaction() will inserted the function code between the START and COMMIT.

But this way return an error :

Parse error: syntax error, unexpected T_FUNCTION

This error is in line where i wrote :

create_transaction($obj, function() { // Error here

Answer Source

What you are doing is calling an 'anonymous function'. You are passing the anonymous (which is anonymous because it's unnamed) to another function that invokes it. However, you're not actually invoking it! Specifically because you have encoded $c; rather than $c().

This works as expected:


function execute_closure($f) {
  echo "Before executing enclosure.\n";

  $f(); //The parens cause php to execute the function

  echo "After executing enclosure.\n";

execute_closure(function() {
  echo "Executing enclosured function.\n";

Placing this in a file called callfunction.php and executing it yields:

$ php callfunction.php  
Before executing enclosure. 
Executing enclosured function. 
After executing enclosure.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download