Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call all php functions in array

If I have a array named myFunctions, contains php function names like this...

$myFunctions= array("functionA", "functionB", "functionC", "functionD",....."functionZ");

How can I call all of that functions using that array?

like image 616
Khaneddy2013 Avatar asked Aug 30 '14 03:08

Khaneddy2013


People also ask

Can you put functions in an array PHP?

By using closure we can store a function in a array. Basically a closure is a function that can be created without a specified name - an anonymous function.

Can we call function in array?

It is important to remember that when an array is used as a function argument, its address is passed to a function. This means that the code inside the function will be operating on, and potentially altering, the actual content of the array used to call the function.

How do you call an array in PHP?

Array elements can be accessed using the array[key] syntax. ); var_dump($array["foo"]); var_dump($array[42]);

What is Array_keys () used for in PHP?

The array_keys() is a built-in function in PHP and is used to return either all the keys of and array or the subset of the keys. Parameters: The function takes three parameters out of which one is mandatory and other two are optional.


2 Answers

You can use variable functions

PHP supports the concept of variable functions. This means that if a variable name has parentheses appended to it, PHP will look for a function with the same name as whatever the variable evaluates to, and will attempt to execute it. Among other things, this can be used to implement callbacks, function tables, and so forth.

foreach($myFunctions as $func) {
    $func();
}
like image 139
John Conde Avatar answered Nov 14 '22 23:11

John Conde


Another way using call_user_func

foreach($myFunctions as $myFunction) {
    call_user_func($myFunction);
}

or

array_walk($myFunctions,'call_user_func');
like image 31
FuzzyTree Avatar answered Nov 14 '22 23:11

FuzzyTree