Leo Tahk Leo Tahk - 1 year ago 84
PHP Question

How to call a function with other function as argument

im just learning php
Im trying to add a log with comments to my functions output.
Right now it looks like this:

//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); };

Im kinda annoyed by the fact i need to retype this if statement.
So i made a seperate function for returning the function
which looks like this:

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

And returning it with:

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

Now my quastion is: Is there a way to call a function with function..


so i can return it either with log or without..

Answer Source

Given the answer https://stackoverflow.com/a/2700760/5387193 - this should work:

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

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

On a side note, your variable and function names aren't very intuitive. Perhaps you should study how to write good quality readable code. I recommend reading chapter 9 of Refactoring by Martin Fowler, it's quite good. You can find a PDF version on the web.

Another note, your return statement return $return = isset($log) ? log_return($data, $log) : log_return($data); has a unnecessary assignment to $return. The code should simply read

return isset($log) ? log_return($data, $log) : log_return($data);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download