Spencer
Spencer

Reputation: 22418

Create PHP function that takes function as a parameter

I am trying to create a PHP function that takes another PHP function as input. Here is an example:

function getMean(function){
    $allUsers =  getAllUsers();
    $sum = 0;

    foreach ($allUsers  as $currentUser ){

        $sum =+ (function($currentUser['CONSUMER_ID'], 5, 8))/(8-5);

    }

}

Upvotes: 2

Views: 355

Answers (7)

prodigitalson
prodigitalson

Reputation: 60413

If you want to dynamically create a function in php < 5.3 then youre stuck with using create_function. Becuase of how you use this function its really insane to use it for anything but but creating simple function for array_map,array_walk or things that do simple calculations or basic text processing.

If youre doing anything more complex than that its much easier and less of a headache to simply define the function as normal and then use it with call_user_func or call_user_func_array as others have suggested.

DO NOT USE eval :-)

Upvotes: 0

Savageman
Savageman

Reputation: 9487

You need PHP 5.3 to do that natively.

function getMean($function){
    $allUsers =  getAllUsers();
    $sum = 0;

    foreach ($allUsers  as $currentUser ){

        $sum += ($function($currentUser['CONSUMER_ID'], 5, 8))/(8-5);
    }
    return $sum;
}

getMean(function($consumer_id, $five, $eight) {
    return $consumer_id;
});

I you run PHP 5.3- (lower than 5.3), you need to use a callback (documentation is here) along with the call_user_func() or call_user_func_array() function.

Upvotes: 2

Felix Geenen
Felix Geenen

Reputation: 2707

are you searching for anonymous functions?

Felix

Upvotes: 0

Richard Parnaby-King
Richard Parnaby-King

Reputation: 14891

Save the function as a variable.

$function = function($param1){ //code here }

and pass it to your other function as a parameter.

function getMean($function)
{
  //code here
  $sum += $function($param);
}

[edit]

PHP.net Manual - Variable Functions

Upvotes: 0

Riimu
Riimu

Reputation: 1437

Perhaps something like this should do it. PHP has a "type" called callback, which can be a closure (as of PHP 5.3), name of a function or array containing object and the method to call. These callbacks can be called with call_user_func()

function getMean($callback){
    $allUsers =  getAllUsers();
    $sum = 0;

    foreach ($allUsers  as $currentUser ){
        $sum =+ (call_user_func($callback, $currentUser['CONSUMER_ID'], 5, 8))/(8-5);
    }

    return $sum;
}

Upvotes: 4

MikeMurko
MikeMurko

Reputation: 2233

It looks like the PHP Eval function is what you are looking for. Pass the getMean function a string, and then change the line to have $sum =+ (eval($param) .....)

Security is a problem though because any function can be passed.

Upvotes: 0

Naftali
Naftali

Reputation: 146360

you can do that as long as function($currentUser['CONSUMER_ID'], 5, 8) returns something

Upvotes: 0

Related Questions