在PHP中,我们可以这样做吗?
function foo($c) {
$c;
echo 'done';
}
foo(function() {
echo 'test'
});
这样输出将是:
testdone
这是我真正的问题:
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);
}
}
所以我可以这样调用create_transaction的这个函数:
create_transaction($obj, function() {
echo 'test';
// this should be a database CRUD process
// to make it simple, i just put echo.
}, 'error');
create_transaction()将在START和COMMIT之间插入功能代码。
但这种方式会返回错误:
Parse error: syntax error, unexpected T_FUNCTION
这个错误与我写的一致:
create_transaction($obj, function() { // Error here
答案 0 :(得分:0)
您正在做的是致电'anonymous function'。您将匿名(匿名,因为它未命名)传递给另一个调用它的函数。但是,你实际上并没有调用它!特别是因为您编码了$c;
而不是$c()
。
这可以按预期工作:
<?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";
});
将其放在名为callfunction.php
的文件中并执行它会产生:
$ php callfunction.php
Before executing enclosure.
Executing enclosured function.
After executing enclosure.
最后要注意:匿名函数仅适用于PHP 5.3 +。
答案 1 :(得分:0)
<?php
function foo($c) {
// CALL THE CALLABLE HERE INSTEAD
try{
$strVal = $c();
if(is_string($strVal)){
echo $strVal . 'done';
}else{
// YOUR FUNCTION IS NOT RETURNING A STRING: CATCH & HANDLE THAT CASE:
echo "The passed-in Argument Must return a String value...";
return false;
}
}catch(Exception $e){
// HANDLE THE EXCEPTION YOUR WAY.
echo "The passed-in Argument Must be a Callable Function and should return a String value...";
}
}
foo(function() {
//RETURN THE VALUE HERE!!!
return "test";
});
// SHOULD ECHO BACK 'testdone' TO THE OUTPUT STREAM...