0

Is the a way in php to create a function which executes provided function (as an arguments) with provided argument (of the provided function - as an array).

Here is some code:

class Worker
{
    public function execute($func, $paramsArr)
    {
        php_func_executer($func, $paramsArr); //the function that I would like to have
    }
}

in other php file I will do as follow:

Class SomeClass 
{
    public function test($varA, $varB)
    {
         //do something
    }

    public function exeText()
    {
       ...
       $worker = new Worker();
       $worker->execute(test, [$varA, $varB]);
    }
}

I know about call_user_func_array but here I don't want to pass the name of the function (as string), I want to pass the function itself (as seen in the code above)

Thanks!

4
  • 4
    first argument of call_user_func_array is any callable, so you can pass a function to it, not name only. Commented Dec 6, 2014 at 17:39
  • even if it is not in the same file? the second argument is an array of arguments? Commented Dec 6, 2014 at 17:40
  • You should explain what do you mean by passing a function? You don;t want to pass a string with function name, so what do you want to pass - array? variable with anonymous function or what? Commented Dec 6, 2014 at 17:44
  • You can see in my second code block what I meant, but I think the answer is already posted here. Thanks Commented Dec 6, 2014 at 17:48

2 Answers 2

1

You can pass the function name as a string and call it.

function execute($func, $paramsArr)
    {
        $func($paramsArr[0], $paramsArr[1]);
    }

function func($par1, $par2)
    {
        echo $par1." ".$par2;
    }


execute('func' , array('a','b'));
Sign up to request clarification or add additional context in comments.

Comments

1

call_user_func_array will do the job

$func = function($a, $b) {
    return $a+$b;
};

echo call_user_func_array($func, [1, 2]); // 3

1 Comment

I downvoted this because OP said this : I know about call_user_func_array but here I don't want to pass the name of the function (as string), I want to pass the function itself (as seen in the code above). So this is not an answer to the question

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.