即时学习php 即时通讯我试图添加一个带有注释的日志到我的函数输出。 现在它看起来是这样的:如何以其他函数作为参数调用函数
//the function
function add1($x){
if($GLOBALS['logging'] === 'on'){ $log[] = 'Adding 1 to '.$x;};
$a = $x + 1;
if($GLOBALS['logging'] === 'on'){
$return[] = $a;
$return[] = $log;
return $return;
}else{ return $a; };
};
//calling the function
if($GLOBALS['logging'] === 'on'){
$return = add1($x);
$number = $return[0];
$log = $return[1];
}else{ $number = add1($x); };
林有点的事实,我需要的if语句重新键入此恼火。 所以我做了一个单独的函数返回函数 看起来像这样:
//function
function log_return($data = 'x', $log = 'x'){
if($GLOBALS['logging'] === 'on'){
if($data !== 'x') $return[] = $data;
if($log !== 'x') $return[] = $log;
return $return;
} return $data;
};//function end
而且随着其返回:
return $return = isset($log) ? log_return($data, $log) : log_return($data);
现在我quastion是:有没有一种方法来调用一个函数功能.. 像:
call_function(add1($x));
,所以我可以用任何日志或不回吧..
可能的重复:https://stackoverflow.com/questions/2700433/accept-function-as-parameter-in-php – ChickenFeet
不要使用$ GLOBALS。将你需要的参数传递给你的函数。这是更安全的自我记录,并且可以捕获错误,特别是如果您使用现在可在PHP中使用的类型提示。 – gview
这就是许多框架围绕依赖注入模式构建的原因。我强烈建议:http://fabien.potencier.org/what-is-dependency-injection.html – gview