← Back to PHP Course | Chapter 5: Functions | Lesson 5 of 10

PHP Variable Functions

Introduction to Variable Functions

If a variable holds a string and you append () to it — $fn() — PHP looks for a function whose *name* matches that string's current value and calls it. This indirection is what lets you decide, at runtime, which of several functions to invoke based on data rather than hardcoded logic.

Example: Introduction to Variable Functions

php
<?php
function sayHello() {
    echo "Hello!";
}
$fn = "sayHello";
$fn();
?>

Variable Object Methods

The same mechanism extends to object methods: storing a method name as a string in a variable and calling $object->$methodName() invokes that method dynamically, without the calling code needing to hardcode which specific method to run.

Example: Variable Object Methods

php
<?php
class Greeter {
    function hello() {
        echo "Hi there!";
    }
}
$obj = new Greeter();
$methodName = "hello";
$obj->$methodName();
?>

Variable Static Methods

You can dynamically call a class's static method the same way, by holding either the class name, the method name, or both as strings and combining them at call time — useful for dispatch tables that route to different handlers based on runtime data.

Example: Variable Static Methods

php
<?php
class Math {
    static function square($n) {
        return $n * $n;
    }
}
$class = "Math";
$method = "square";
echo $class::$method(4);
?>

Checking Before Calling

Before calling anything this way, check is_callable($value) first. Attempting to invoke a string that doesn't actually correspond to any real function or method throws a fatal error rather than failing gracefully, so validating first prevents a crash from a bad or mistyped name.

Example: Checking Before Calling

php
<?php
$fn = "strtoupper";
if (is_callable($fn)) {
    echo $fn("hello");
}
?>

Variable Functions in Callbacks

Passing a string function name to something like array_map() or usort() as a callback relies on exactly this variable-function mechanism under the hood — PHP resolves the string to an actual function to call for each element, without you writing an explicit dispatch step yourself.

Example: Variable Functions in Callbacks

php
<?php
function double($n) {
    return $n * 2;
}
$numbers = [1, 2, 3];
$doubled = array_map("double", $numbers);
print_r($doubled);
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.