In what scenarios would it be appropriate to use dynamic function calls based on form submissions in PHP, and how can this be implemented securely?

When dealing with form submissions in PHP, it may be appropriate to use dynamic function calls based on the submitted form data to handle different actions. This can be useful for creating a more modular and scalable codebase. However, it is crucial to implement this securely to prevent vulnerabilities such as code injection attacks. One way to do this is by using a whitelist approach to validate and sanitize the input before dynamically calling the function.

// Example of securely implementing dynamic function calls based on form submissions

// Define an array of allowed functions
$allowedFunctions = ['function1', 'function2', 'function3'];

// Get the form submission data
$action = isset($_POST['action']) ? $_POST['action'] : '';

// Validate the submitted action against the whitelist
if (in_array($action, $allowedFunctions)) {
    // Call the function dynamically
    $action();
} else {
    // Handle invalid actions
    echo "Invalid action";
}

// Define the functions to be called dynamically
function function1() {
    // Function logic for action 1
}

function function2() {
    // Function logic for action 2
}

function function3() {
    // Function logic for action 3
}