Marcel Ang Marcel Ang - 6 months ago 9
PHP Question

PHP function as parameter of another function

In PHP can we do this?

function foo($c) {
$c;

echo 'done';
}

foo(function() {
echo 'test'
});


Such that the output will be:

testdone





This was my real problem :

function create_transaction($obj, $func, $errorMsg)
{
try {
$obj->transaction('START');

$func();

$obj->transaction('COMMIT');
} catch(Exception $e) {
$obj->transaction('ROLLBACK');
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

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:

<?php

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.