1

Can I make an array of functions and execute the functions with a foreach loop?

Like:

// This is the beginning of the php file
global $actions = array();

// This is the function where functions need to be added.
function HeadFunction(){
 foreach($actions as $action) 
 $action;
}

This is the function to add the action

function add_action($action){
global $actions;
$actions[] = $action;
}

This is a example function:

function check_Url(){
 if(isset($_GET['gettest'])){
    echo '<script>alert(\'This is a test\');</script>';
 }
}

and then add the function with: add_action(check_Url());

Neil Yoga Crypto
  • 615
  • 5
  • 16

1 Answers1

0

Use call_user_func.

global $actions = array();

function add_action($action){
global $actions;
$actions[] = $action;
}

add_action('check_Url');
add_action('function2');

foreach ($actions AS $action) {
    call_user_func($action);
}
David Xu
  • 5,555
  • 3
  • 28
  • 50
  • Thank you David Xu! Sheikh Heera pointed out that $action should be $action(), and it worked. What do you think is better way? Adding strings to $actions[] to call $action() vs adding functions to $actions[] and call call_user_func($action)? – Neil Yoga Crypto Mar 09 '14 at 21:01