PHP variable functions allow a variable to hold the name of a function and call it dynamically. This enables flexible and dynamic execution of functions at runtime.
// Store function name in a variable and call it
$functionName = 'someFunction';
$functionName();
Call a function dynamically using a variable:
// Define a simple function
function sayHello() {
echo "Hello, World!";
}
// Assign function name to variable and call it
$func = 'sayHello';
$func();
You can also pass arguments to functions via variable functions:
// Function with parameter
function greet($name) {
echo "Hello, $name!";
}
// Call function dynamically with argument
$func = 'greet';
$func('Alice');
// Define multiple operations
function add($a, $b) {
return $a + $b;
}
function multiply($a, $b) {
return $a * $b;
}
// Choose operation dynamically
$operation = 'multiply';
echo $operation(5, 10);
The selected function name stored in a variable is executed at runtime, producing output based on the chosen logic.
Think of variable functions like a remote control — the button you press (variable value) decides which action (function) runs.
is_callable()