Skip to main content

PHP pass function as param then call the function?



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!



Source: Tips4all

Comments

  1. 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");
    ?>

    ReplyDelete
  2. 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.

    ReplyDelete
  3. In php this is very simple.

    <?php

    function here() {
    print 'here';
    }


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

    //Will work
    dynamo('here');
    //Will fail
    dynamo('not_here');

    ReplyDelete
  4. 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.

    ReplyDelete

Post a Comment

Popular posts from this blog

Slow Android emulator

I have a 2.67 GHz Celeron processor, 1.21 GB of RAM on a x86 Windows XP Professional machine. My understanding is that the Android emulator should start fairly quickly on such a machine, but for me it does not. I have followed all instructions in setting up the IDE, SDKs, JDKs and such and have had some success in staring the emulator quickly but is very particulary. How can I, if possible, fix this problem?