Variable Functions

Ma Mahalakshmi V Updated 14 Nov 2026
6 min read ·Lesson 73 of 256

What Are Variable Functions?

In simple terms: A variable function is a function call where the function's name is stored in a variable. When PHP sees parentheses after a variable, it calls the function whose name the variable contains.

Technically: If a variable holding a string is followed by (...), PHP looks up a function with that name and calls it. The same mechanism works for methods ($object->$method()), static methods ($class::$method()), and other callables such as closures and [$object, 'method'] arrays.

$fn = 'strtoupper';
echo $fn('php');   // calls strtoupper('php')

Why They Exist

Variable functions let a program decide at runtime which function to call — for example, choosing an export format, a payment handler, or a validation rule based on configuration or data. They are also the foundation of callbacks: passing a function to another function, as array_map() and usort() do.


Basic Usage

Example

<?php
$transform = 'strtoupper';
echo $transform('learn php') . "\n";

$transform = 'ucwords';
echo $transform('learn php') . "\n";

function addStars(string $text): string
{
    return "★ $text ★";
}

$transform = 'addStars';
echo $transform('learn php') . "\n";

Output

LEARN PHP
Learn Php
★ learn php ★

How It Works

  1. $transform holds the string 'strtoupper'.
  2. $transform('learn php') makes PHP call the function named by that string.
  3. Assigning a different name changes which function runs — the calling code stays the same.
  4. Both built-in and user-defined functions can be called this way.

Choosing a Function From Data: Dispatch Tables

The most practical use of variable functions is a dispatch table: an array that maps keys to the functions that handle them.

<?php
function add(float $a, float $b): float { return $a + $b; }
function subtract(float $a, float $b): float { return $a - $b; }
function multiply(float $a, float $b): float { return $a * $b; }

function calculate(string $operator, float $a, float $b): string
{
    $operations = [
        '+' => 'add',
        '-' => 'subtract',
        '*' => 'multiply',
    ];

    if (!isset($operations[$operator])) {
        return "Unsupported operator: $operator";
    }

    $operation = $operations[$operator];

    return "$a $operator $b = " . $operation($a, $b);
}

echo calculate('+', 5, 3) . "\n";
echo calculate('*', 4, 2.5) . "\n";
echo calculate('/', 8, 2) . "\n";

Output

5 + 3 = 8
4 * 2.5 = 10
Unsupported operator: /

Why This Pattern Is Safe

  • The input ($operator) is used only as a key in a fixed array. The function names come from your own code.
  • Unknown operators are rejected before any function is called.
  • Adding an operation means adding one line to the table — no growing if/elseif chain.

Security warning: Never call a function name taken directly from user input, such as $_GET['action'](). An attacker could call any function available in PHP — for example, functions that delete files or run shell commands. Always map user input to an allow-list of known functions, as shown above.


Variable Methods

The same idea works for methods on objects.

Instance Methods

<?php
$date = new DateTimeImmutable('2026-10-09');

$method = 'format';
echo $date->$method('d M Y') . "\n";

$formats = ['Y-m-d', 'l', 'D, j M'];
foreach ($formats as $format) {
    echo $date->$method($format) . "\n";
}

Output

09 Oct 2026
2026-10-09
Friday
Fri, 9 Oct

$date->$method(...) calls the method whose name is stored in $method.

Static Methods

<?php
$class = 'DateTimeImmutable';
$factory = 'createFromFormat';

$date = $class::$factory('d/m/Y', '15/10/2026');

echo $date->format('Y-m-d') . "\n";

Output

2026-10-15

Both the class name and the method name can come from variables.


Callables: Functions as Values

A callable is anything PHP can call. Variable functions are one kind; there are several others:

Callable FormExample
Function name string'strtoupper'
Static method string'DateTimeImmutable::createFromFormat'
Object + method array[$date, 'format']
Class + static method array['DateTimeImmutable', 'createFromFormat']
Closure (anonymous function)function ($x) { ... } or fn($x) => ...
First-class callable (PHP 8.1+)strtoupper(...), $date->format(...)
Invokable objectAn object of a class with an __invoke() method

Example

<?php
$date = new DateTimeImmutable('2026-10-09');

$dayName = [$date, 'format'];
echo $dayName('l') . "\n";

$upper = 'strtoupper';
$names = ['asha', 'bala'];
print_r(array_map($upper, $names));

var_dump(is_callable('strtoupper'));
var_dump(is_callable('noSuchFunction'));
var_dump(is_callable([$date, 'format']));

Output

Friday
Array
(
    [0] => ASHA
    [1] => BALA
)
bool(true)
bool(false)
bool(true)
  • [$date, 'format'] is an array callable: calling it runs $date->format('l').
  • array_map() accepts any callable, including a function name string.
  • is_callable() checks whether a value can be called — useful before calling a dynamically chosen function.

The modern way to create callables from existing functions is first-class callable syntax (strtoupper(...)), which IDEs and static analysis tools understand better than strings. See First-class Callable Syntax.


call_user_func() and call_user_func_array()

These functions call any callable:

<?php
echo call_user_func('str_repeat', 'ab', 3) . "\n";
echo call_user_func_array('max', [4, 9, 2]) . "\n";

Output

ababab
9

In modern PHP, the direct forms are usually preferred:

Older FormModern Equivalent
call_user_func($fn, $a, $b)$fn($a, $b)
call_user_func_array($fn, $args)$fn(...$args)

What Cannot Be Called Dynamically

Language constructs are not functions, so they cannot be called through a variable: echo, print, isset, empty, unset, include, require, list, and exit/die (in PHP versions before 8.4, where exit became a real function).

<?php
$output = 'echo';

try {
    $output('Hello');
} catch (Error $e) {
    echo get_class($e) . ": " . $e->getMessage() . "\n";
}

Output

Error: Call to undefined function echo()

Wrap such constructs in a real function or closure if you need to pass them around: $output = fn(string $s) => print $s;.

Calling a name that does not exist produces the same kind of error ("Call to undefined function ..."), which is why dynamic calls should be checked with an allow-list or is_callable().


Practical Example: Export Formats

<?php
function exportCsv(array $rows): string
{
    $lines = [implode(',', array_keys($rows[0]))];

    foreach ($rows as $row) {
        $lines[] = implode(',', $row);
    }

    return implode("\n", $lines);
}

function exportJson(array $rows): string
{
    return json_encode($rows);
}

function export(array $rows, string $format): string
{
    $exporters = [
        'csv' => 'exportCsv',
        'json' => 'exportJson',
    ];

    $exporter = $exporters[strtolower($format)]
        ?? throw new InvalidArgumentException("Unsupported format: $format");

    return $exporter($rows);
}

$rows = [
    ['id' => 1, 'name' => 'Asha'],
    ['id' => 2, 'name' => 'Bala'],
];

echo export($rows, 'csv') . "\n\n";
echo export($rows, 'JSON') . "\n";

Output

id,name
1,Asha
2,Bala

[{"id":1,"name":"Asha"},{"id":2,"name":"Bala"}]

Step-by-Step Explanation

  1. Each format has its own small function with the same signature: it receives rows and returns a string.
  2. export() maps the requested format (case-insensitively) to a function name. Unknown formats throw an exception — throw can be used as an expression after ?? since PHP 8.0.
  3. $exporter($rows) calls the selected function.
  4. Adding an XML or Excel export later only requires a new function and one new table entry.

This simplified CSV writer does not handle commas or quotes inside values; real code should use fputcsv() (see Concatenate Strings). In object-oriented code, the same idea is usually implemented with classes that share an interface (see PHP Interfaces).


Common Mistakes

Calling User-Supplied Function Names

Effect: Attackers can execute arbitrary functions.

Fix: Map input to an allow-list of known callables.

Calling Language Constructs Dynamically

Effect: "Call to undefined function echo()".

Fix: Wrap the construct in a function or closure.

Typos in Function Name Strings

Effect: Runtime error, invisible to editors and static analysis.

Fix: Prefer first-class callables (strtoupper(...)) or closures, which tools can check.

Overusing Dynamic Calls

Effect: "Find usages" and refactoring tools cannot see which functions are called, and code becomes hard to follow.

Fix: Use dynamic calls only where runtime selection is genuinely needed.


Best Practices

  • Use dispatch tables (allow-lists) to choose functions based on data.
  • Check dynamic callables with is_callable() when the source is not fully controlled.
  • Prefer $fn(...$args) over call_user_func_array().
  • Prefer closures and first-class callable syntax over function-name strings in new code.
  • Keep handler functions consistent in signature so they are interchangeable.

Official reference: https://www.php.net/manual/en/functions.variable-functions.php

0 Comments

Reviewed before they appear

No comments yet.

PHP
PHP Tutorial Index PHP Home PHP Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope Static Variables Variable Variables PHP Echo / Print PHP printf / sprintf PHP Data Types PHP Booleans PHP NULL PHP Strings String Functions Modify Strings Concatenate Strings Slicing Strings Escape Characters String Interpolation Heredoc and Nowdoc Search in Strings Multibyte Strings PHP Floats PHP Casting PHP Type Juggling PHP Math PHP Random Numbers PHP Constants PHP Magic Constants PHP Operators Arithmetic Operators Assignment Operators Comparison Operators Increment / Decrement Operators Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence PHP If...Else...Elseif PHP If PHP If Operators PHP If...Else PHP Shorthand if PHP Nested if PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement Continue Statement PHP Functions User-defined Functions Function Arguments Default Argument Values Pass by Reference Named Arguments Variadic Functions Return Values Type Declarations in Functions Recursive Functions Variable Functions Anonymous Functions Closures Arrow Functions First-class Callable Syntax PHP Arrays Indexed Arrays Associative Arrays Create Arrays Access Array Items Update Array Items Add Array Items Remove Array Items Sorting Arrays Multidimensional Arrays Array Destructuring Array Spread Operator Search in Arrays Merge Arrays array_map / array_filter / array_reduce Array Functions PHP Superglobals $GLOBALS $_SERVER $_REQUEST $_POST $_GET $_FILES $_COOKIE $_SESSION \$\_ENV PHP RegEx RegEx Patterns RegEx Modifiers preg_match preg_replace preg_split PHP RegEx Functions PHP Form Handling PHP Form Validation PHP Form Required PHP Form URL/E-mail Form Input Sanitizing Escaping Output (htmlspecialchars) Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting DateTime Class Timezones PHP Include Include vs Require PHP File Handling PHP File Open/Read PHP File Create/Write File Delete / Rename / Copy PHP Directories PHP CSV Files PHP File Upload PHP Cookies PHP Sessions PHP Filters PHP Filters Advanced PHP Callback Functions PHP JSON PHP Exceptions Error Handling Custom Error Handler Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators PHP What is OOP PHP Classes/Objects The $this Keyword PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Destructor PHP Access Modifiers Readonly Properties PHP Inheritance Method Overriding The final Keyword PHP Class Constants PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning Comparing Objects Anonymous Classes PHP Enums PHP Namespaces Autoloading Classes PHP Iterables Iterators Object Serialization Strict Types Union Types Nullable Types Mixed and Never Types Nullsafe Operator PHP Attributes PHP Fibers Readonly Classes Property Hooks (PHP 8.4) Asymmetric Visibility (PHP 8.4) Reflection API SPL Data Structures MySQL Database MySQL Connect MySQL Create DB MySQL Create Table MySQL Insert Data MySQL Get Last ID MySQL Insert Multiple MySQL Prepared MySQL Select Data MySQL Where MySQL Order By MySQL Delete Data MySQL Update Data MySQL Limit Data MySQL Joins with PHP Pagination with PHP PDO Introduction PDO Connect PDO Prepared Statements PDO Fetch Modes PDO Transactions PDO Error Handling PHP XML Parsers PHP SimpleXML Parser PHP SimpleXML - Get PHP XML Expat Parser PHP DOM Parser PHP XMLReader PHP XMLWriter AJAX Intro AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention CSRF Protection Session Security Secure Cookies File Upload Security Filesystem Security Error Reporting in Production Hiding PHP Encryption with Sodium PHP Configuration (php.ini) PHP Command Line (CLI) Composer PSR-4 Autoloading Installing Extensions (PECL / PIE) Debugging PHP OPcache & Performance Garbage Collection PHP-FPM Migrating to PHP 8 Project: Contact Form with Email Project: Login & Registration System Project: CRUD App with MySQL Project: Image Upload Gallery Project: Shopping Cart with Sessions Project: Simple Blog Project: REST API with PHP
Ask about this post
AI Ask about this post

Ask questions about Variable Functions and get answers drawn from it.

Signed-in readers only.