2017-08-28 120 views
0

即时学习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)); 

,所以我可以用任何日志或不回吧..

+0

可能的重复:https://stackoverflow.com/questions/2700433/accept-function-as-parameter-in-php – ChickenFeet

+1

不要使用$ GLOBALS。将你需要的参数传递给你的函数。这是更安全的自我记录,并且可以捕获错误,特别是如果您使用现在可在PHP中使用的类型提示。 – gview

+1

这就是许多框架围绕依赖注入模式构建的原因。我强烈建议:http://fabien.potencier.org/what-is-dependency-injection.html – gview

回答

1

给出了答案https://stackoverflow.com/a/2700760/5387193 - 这应该工作:

function add1($a) 
{ 
    // add1 code goes here 
} 

function call_function($name, $param) 
{ 
    $name($param); 
} 
call_function('add1', $x); 

在一个侧面说明,你的变量和函数名是不是很直观。也许你应该学习如何编写高质量的可读代码。我推荐阅读Martin Fowler的“重构”第9章,它非常好。您可以在网上找到PDF版本。

另请注意,您的返回语句return $return = isset($log) ? log_return($data, $log) : log_return($data);对$ return有不必要的分配。代码应该简单阅读

return isset($log) ? log_return($data, $log) : log_return($data); 
1

是的,这是可能的。为了简化:

function first($x) { 
    return $x+1; 
} 
function second($y) { 
    return $y+1; 
} 
echo second(first(1)); // Returns 3, ie. 1+1+1 
1

正如gview在他的评论中所说的,不要使用全局变量。参数列表的存在有几个原因,包括但不限于使代码更易于阅读,编辑和调试。功能和变量名称也是如此。

此外,你的代码非常混乱。它可以合并:

function addTo($currentValue, $valueToAdd, $logging = 0) 
{ 
    if ($logging) { 
     logWrite('addTo', "Adding $valueToAdd to $currentValue"); 
     return $currentValue + $valueToAdd; 
    } else { 
     return $currentValue; 
    } 
} 

function logWrite($operation, $message) 
{ 
    $log = getLog(); // maybe it's a file, or DB record or something 
    // perform the write, depending on your implementation 
} 

$number = addTo($someStaringValue, $someOtherValue, 1); 

所有这一切都表示,日志记录不应该控制程序流。换句话说,不管系统是否记录了什么,都不应该影响你的代码试图做什么。我真的认为你需要更广泛地了解你想要做什么,并将其分解成组件。

充其量,您的代码应该告诉记录器记录信息,并且记录器本身应该确定是否实际打开记录日志。如果是,则会记录信息。如果没有,那么调用记录器的代码仍然工作并开始其业务。

+0

感谢您的答复,我会重写代码而不使用全局变量,并且是日志已打开(文件或屏幕)开/关。有很多工作要做..试图尽可能地巩固。 –

相关问题