views:

4080

answers:

4

I need to pass a function as a parameter to another function and then call the passed function from withing the function...This is probably easier for me to explain in code..I basically want to do something like this:

function ($functionToBeCalled)
{
   call($functionToBeCalled,additional_params);
}

Is there a way to do that.. I am using PHP 4.3.9

Thanks!

+11  A: 

I think you are looking for call_user_func.

An example from the PHP Manual:

<?php
function barber($type) {
    echo "You wanted a $type haircut, no problem";
}
call_user_func('barber', "mushroom");
call_user_func('barber', "shave");
?>
Paolo Bergantino
+6  A: 
function foo($function) {
  $function(" World");
}
function bar($params) {
  echo "Hello".$params;
}

$variable = 'bar';
foo($variable);

Additionally, you can do it this way. See variable functions.

tj111
I think you're jumping the gun a bit there. IIRC, that code won't start working until PHP 5.3 comes out.
Jeremy DeGroot
“bar” has to be quoted since it’s a string.
Gumbo
@Jeremy DeGroot variable functions have been around forever
Greg
I forgot the quotes, thanks for pointing that out. Added them in the edit. You can do it without quotes in 5.3?
tj111
You can do it without quotes in older versions of PHP. It turns the unknown symbol into a string, and issues a warning (assuming appropriate reporting) due to the behavior being depreciated (?).
strager
@tj111, if PHP comes across an unknown CONSTANT it will assume you meant a string.
Pim Jager
+4  A: 

In php this is very simple.

<?php

function here() {
  print 'here';
}


function dynamo($name) {
 $name();
}

//Will work
dynamo('here');
//Will fail
dynamo('not_here');
Stewart Robinson
+2  A: 

You could also use call_user_func_array() it allows you to pass an array of parameters as the second parameter so you don't have to know exactly how many variables you're passing.