Skip to content

Instantly share code, notes, and snippets.

@pierrejoubert73
Last active October 14, 2016 08:43
Show Gist options
  • Save pierrejoubert73/f334880c910e983da6b4d4765e46da8f to your computer and use it in GitHub Desktop.
Save pierrejoubert73/f334880c910e983da6b4d4765e46da8f to your computer and use it in GitHub Desktop.
How to dynamically call functions with x amount of parameters.
<?php
$results = array();
# The "$selected_functions" array will be constructed on the client side and posted to the PHP controller function.
# Populate the "$selected_functions" array based on user interaction with the UI.
$selected_functions = array(
"function_1" => array("parameter_1_1", "parameter_1_2", "parameter_1_3"),
"function_2" => array("parameter_2_1"),
"function_3" => array("parameter_3_1", "parameter_3_2")
);
# The "$array_of_functions" array contains all function defintitions.
$array_of_functions = array(
"function_1" => function($parameter_array_1) {
# Amazing code
return $result;
},
"function_2" => function($parameter_array_2) {
# Amazing code
return $result;
},
"function_3" => function($parameter_array_3) {
# Amazing code
return $result;
}
);
# We loop through the "$selected_functions" array to determine which functions must be invoked.
# Use "$key" to refer to the function name and "$value" to refer to the array of parameters.
# "$key" is used to select the "assocative index" from "$array_of_functions".
# "$parameters" is simply passed as a paramter.
# With default naming: foreach($array as $key => $value)
foreach($selected_functions as $function => $parameters)
{
$results[$function] = $array_of_functions[$function]($parameters);
}
# Process "$results"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment