Sometimes a function name is not known until the code is running. You may choose an action from a configuration value, route a request to a handler, or pick a formatter based on some condition. Writing a long chain of if statements for that gets old rather quickly.
PHP variable functions solve this neatly. Store the function name in a variable, add parentheses, and PHP calls that function.
This is different from functions that inspect or convert PHP variables. A variable function specifically means calling a function through a variable. It works with user-defined functions, many built-in functions, object methods, static methods, and other PHP callables.
What is a variable function in PHP?
A PHP variable function is a function call where the function name comes from a variable.
<?php
$functionName = 'strlen';
$length = $functionName('PHP');
echo $length;
The output is:
3
Here, $functionName contains the string strlen. When PHP evaluates $functionName('PHP'), it calls strlen('PHP').
The same syntax works with your own PHP functions.
<?php
function greet(string $name): string
{
return "Hello, " . $name;
}
$functionName = 'greet';
echo $functionName('Sam');
This prints:
Hello, Sam
The basic pattern is simply:
$functionName = 'someFunction';
$functionName($argument);
PHP describes this behavior as variable functions. The useful part is not saving a few characters. It is being able to choose the callable at runtime.
Passing arguments and receiving return values
A variable function behaves like a normal function call. You can pass arguments and use its return value in exactly the same way.
<?php
function calculateTax(float $amount, float $rate): float
{
return $amount * $rate;
}
$calculator = 'calculateTax';
$tax = $calculator(1500, 0.18);
echo $tax;
The variable changes how PHP finds the function. It does not change how parameters, return types, or return values work.
This distinction is useful because variable functions are not a separate kind of function. They are a dynamic way of calling an existing callable.
Calling object methods with variable names
Variable functions are not limited to standalone functions. PHP also lets you store a method name in a variable and call it on an object.
<?php
class TextFormatter
{
public function uppercase(string $text): string
{
return strtoupper($text);
}
public function lowercase(string $text): string
{
return strtolower($text);
}
}
$formatter = new TextFormatter();
$method = 'uppercase';
echo $formatter->$method('Hello PHP');
The output is:
HELLO PHP
PHP reads $formatter->$method(), gets the method name from $method, and then calls that method on the object.
This becomes useful when several methods share the same purpose or interface and your code needs to choose one at runtime.
<?php
$method = 'lowercase';
echo $formatter->$method('Hello PHP');
Now PHP calls lowercase() instead.
Calling static methods dynamically
Static method names can also come from variables.
<?php
class PriceFormatter
{
public static function rupees(float $amount): string
{
return '₹' . number_format($amount, 2);
}
public static function dollars(float $amount): string
{
return '$' . number_format($amount, 2);
}
}
$method = 'rupees';
echo PriceFormatter::$method(1250);
This prints:
₹1,250.00
You can also keep the class name in a variable when the design genuinely requires it.
<?php
$className = PriceFormatter::class;
$method = 'dollars';
echo $className::$method(1250);
Dynamic class and method names can make extensible code easier to build. They can also make code harder to trace if used everywhere. Use them where runtime selection adds real value, not simply because PHP allows it.
Variable functions and PHP callables
In modern PHP, it helps to think in terms of callables. A callable is any value PHP can invoke as a function.
Common callable forms include:
- A function name such as
'strlen'. - An object and method pair such as
[$formatter, 'uppercase']. - A class and static method pair such as
[PriceFormatter::class, 'rupees']. - An anonymous function.
- An arrow function.
For example, an object method can be stored as a callable and invoked later:
<?php
$callback = [$formatter, 'uppercase'];
echo $callback('Variable functions');
The output is:
VARIABLE FUNCTIONS
This style is common when working with callback-based PHP functions such as array_map(), event handlers, routers, and other code that accepts behavior as a value.
<?php
function trimValue(string $value): string
{
return trim($value);
}
$values = [' PHP ', ' MySQL ', ' JavaScript '];
$cleanValues = array_map('trimValue', $values);
print_r($cleanValues);
A variable function is therefore one practical part of PHP’s broader callable system.
Check a dynamic callable before invoking it
If a function or method name comes from a configuration value, database record, or other runtime source, verify it before calling it.
is_callable() is designed for this job.
<?php
$handler = 'strtoupper';
if (is_callable($handler)) {
echo $handler('php');
}
This prints:
PHP
If the value is not callable, you can handle the problem instead of allowing the call to fail.
<?php
$handler = 'missingFunction';
if (!is_callable($handler)) {
echo 'Invalid handler.';
return;
}
echo $handler('PHP');
For method callables, pass the same callable structure that you intend to invoke.
<?php
$callback = [$formatter, 'uppercase'];
if (is_callable($callback)) {
echo $callback('php variable functions');
}
function_exists() is useful when you specifically need to test whether a named function exists. For general dynamic calls, is_callable() is usually the better check because it also works with methods, closures, and other callable forms.
Do not call arbitrary user-supplied function names
Dynamic calls become risky when an external value is treated directly as a function name.
Avoid code like this:
<?php
$action = $_GET['action'] ?? '';
if (is_callable($action)) {
$action();
}
is_callable() only tells you that PHP can invoke the value. It does not tell you that the function is appropriate or safe for your application.
A safer pattern is to map accepted input values to a small list of known callables.
<?php
function showProfile(): void
{
echo 'Profile page';
}
function showOrders(): void
{
echo 'Orders page';
}
$handlers = [
'profile' => 'showProfile',
'orders' => 'showOrders',
];
$action = $_GET['action'] ?? '';
if (!isset($handlers[$action])) {
echo 'Unknown action.';
return;
}
$handler = $handlers[$action];
$handler();
This keeps the dynamic behavior while making the allowed choices explicit. In real projects, that small whitelist is often much easier to review than allowing arbitrary function names to travel through the application.
Closures and first-class callables
A callable does not have to be represented by a string. You can store an anonymous function directly in a variable and invoke it with the same syntax.
<?php
$greet = function (string $name): string {
return 'Hello, ' . $name;
};
echo $greet('Sam');
Arrow functions work the same way.
<?php
$double = fn (int $number): int => $number * 2;
echo $double(12);
PHP 8.1 and later also support first-class callable syntax. It lets you obtain a Closure from an existing function or method without writing the callable name as a string.
<?php
$formatter = strtoupper(...);
echo $formatter('php');
The same syntax works with object methods.
<?php
$uppercase = $formatterObject->uppercase(...);
echo $uppercase('variable functions');
First-class callables are useful when you want to pass existing behavior around as a value while keeping the function or method reference explicit in the code.
String-based variable functions are still valid and useful, especially when the callable name genuinely comes from runtime data. When the target is known while writing the code, a closure or first-class callable can often be clearer to static analysis tools and to the next developer reading the file.
A practical handler map example
One of the clearest uses of variable functions is selecting a handler from a known set of actions.
<?php
function createOrder(array $data): string
{
return 'Order created for ' . $data['customer'];
}
function cancelOrder(array $data): string
{
return 'Order cancelled for ' . $data['customer'];
}
$handlers = [
'create' => 'createOrder',
'cancel' => 'cancelOrder',
];
$action = 'create';
if (!isset($handlers[$action])) {
echo 'Unsupported action.';
return;
}
$handler = $handlers[$action];
$result = $handler([
'customer' => 'David',
]);
echo $result;
This prints:
Order created for David
The important part is the handler map:
$handlers = [
'create' => 'createOrder',
'cancel' => 'cancelOrder',
];
The application works with simple action names such as create and cancel, while the map decides which PHP function handles each one.
This pattern is more maintainable than a growing set of conditions when all actions follow the same calling convention.
Common errors with PHP variable functions
Calling a function that does not exist
If the variable contains an invalid function name, PHP cannot perform the call.
<?php
$handler = 'sendNotificaton';
$handler();
A typo in a string is particularly easy to miss because an IDE cannot always validate it as reliably as a normal function call.
Use is_callable() when the value is genuinely dynamic.
<?php
if (!is_callable($handler)) {
echo 'Handler is not callable.';
return;
}
$handler();
Using the wrong argument list
Dynamic invocation does not relax a function’s parameter requirements.
<?php
function multiply(int $first, int $second): int
{
return $first * $second;
}
$operation = 'multiply';
echo $operation(10);
The target function still expects two arguments. Variable functions only make the function selection dynamic. The function signature remains unchanged.
This is one reason handler maps work best when the available functions follow a consistent signature.
Confusing a function name with its result
These two variables contain very different things:
<?php
$functionName = 'strlen';
$result = strlen('PHP');
$functionName contains a callable function name. $result contains the integer 3.
Only the first value can be invoked as a variable function:
<?php
echo $functionName('PHP');
Building too much logic around dynamic names
Variable functions can remove repetitive branching, but too much dynamic dispatch can have the opposite effect. If method and function names are assembled from strings throughout the application, following the execution path becomes difficult.
Prefer a small, explicit callable map when possible:
<?php
$formatters = [
'upper' => 'strtoupper',
'lower' => 'strtolower',
];
$type = 'upper';
if (!isset($formatters[$type])) {
echo 'Unknown formatter.';
return;
}
$formatter = $formatters[$type];
echo $formatter('Php');
This still gives you dynamic behavior, but the possible execution paths remain visible in one place.
When variable functions are a good fit
Variable functions are useful when the program genuinely needs to choose behavior at runtime. Typical examples include callback selection, command handlers, small routing tables, formatter maps, validation rules, and configurable processing steps.
They are less useful when the called function is already known. In that case, a normal function call is usually clearer.
<?php
echo strtoupper('PHP');
There is little benefit in changing that to:
<?php
$function = 'strtoupper';
echo $function('PHP');
The second version adds indirection without solving a problem.
A good rule is simple: use variable functions when the choice of callable is part of the program’s logic. If there is no real choice, keep the direct call.
Variable functions vs call_user_func()
PHP also provides call_user_func() for invoking callables dynamically.
<?php
function greet(string $name): string
{
return 'Hello, ' . $name;
}
echo call_user_func('greet', 'Sam');
The same call is usually simpler with variable function syntax:
<?php
$handler = 'greet';
echo $handler('Sam');
For ordinary dynamic calls, direct callable syntax is easier to read and works naturally with functions, closures, and callable arrays.
call_user_func() still exists and can be useful in older code or APIs built around it. But for new code, there is usually no reason to introduce it when the callable can be invoked directly.
Using call_user_func_array() for a dynamic argument list
A related function, call_user_func_array(), accepts the arguments as an array.
<?php
function total(int $first, int $second, int $third): int
{
return $first + $second + $third;
}
$arguments = [10, 20, 30];
echo call_user_func_array('total', $arguments);
Modern PHP can usually express the same thing more directly with argument unpacking.
<?php
$function = 'total';
$arguments = [10, 20, 30];
echo $function(...$arguments);
This keeps both parts of the operation visible: the selected callable and the arguments passed to it.
PHP variable functions FAQ
Can a PHP variable contain a built-in function name?
Yes. A string such as 'strlen' or 'strtoupper' can be stored in a variable and called dynamically.
<?php
$function = 'strtoupper';
echo $function('php');
Can I call a method name stored in a variable?
Yes. PHP supports dynamic object and static method calls.
<?php
$method = 'save';
$repository->$method();
The method must exist and be accessible in that context.
What is the difference between a variable function and a callback?
A variable function describes the act of invoking a function through a variable. A callback is a callable value passed to other code so that it can be invoked later.
The same callable may be used in both ways.
<?php
$formatter = 'strtoupper';
echo $formatter('php');
$result = array_map($formatter, ['php', 'mysql']);
Should I use function_exists() or is_callable()?
Use function_exists() when you specifically need to know whether a named function has been defined. Use is_callable() when you need to know whether a value can actually be invoked.
That distinction matters for object methods, static methods, closures, and callable arrays.
Are variable functions safe?
They are safe when the callable comes from application-controlled code. The problem appears when arbitrary external input is allowed to decide which PHP function or method runs.
For user-controlled values, map accepted input to known callables instead of invoking the input directly.
Conclusion
PHP variable functions let you choose and invoke functions or methods at runtime. The syntax is small, but it is useful for handler maps, callbacks, formatters, routing logic, and other places where behavior needs to be selected dynamically.
Keep the possible callables explicit when you can. Validate dynamic values with is_callable(), and never treat arbitrary user input as a function name.
Used in the right place, variable functions make PHP code more flexible without making it mysterious. That last part is important. Dynamic code is useful. Detective work at 2 AM is less useful.