PHP Variable Functions
In this page:
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
function sayHello() {
echo "Hello!";
}
$fn = "sayHello";
$fn();
?>
Login to try C/C++/Java/PHP code in the editor
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
class Greeter {
function hello() {
echo "Hi there!";
}
}
$obj = new Greeter();
$methodName = "hello";
$obj->$methodName();
?>
Login to try C/C++/Java/PHP code in the editor
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
class Math {
static function square($n) {
return $n * $n;
}
}
$class = "Math";
$method = "square";
echo $class::$method(4);
?>
Login to try C/C++/Java/PHP code in the editor
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
$fn = "strtoupper";
if (is_callable($fn)) {
echo $fn("hello");
}
?>
Login to try C/C++/Java/PHP code in the editor
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
function double($n) {
return $n * 2;
}
$numbers = [1, 2, 3];
$doubled = array_map("double", $numbers);
print_r($doubled);
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: