PHP Variable functions

Variable functions in PHP allow you to call a function dynamically by storing its name in a variable. When you append parentheses to a variable containing a function name, PHP executes that function. This feature is particularly useful for implementing callbacks, function tables, and dynamic function calls.

Note: Variable functions cannot be used with language constructs like echo, include, require, etc. Use function wrappers as a workaround when needed.

Basic Variable Function

Here's a simple example where a variable stores a function name and calls it ?

<?php
function hello(){
    echo "Hello World";
}
$var = "hello";
$var();
?>
Hello World

Variable Function with Parameters

You can also pass arguments to variable functions ?

<?php
function add($x, $y){
    echo $x + $y;
}
$var = "add";
$var(10, 20);
?>
30

Dynamic Function Selection

Variable functions enable dynamic function selection based on user input or conditions ?

<?php
function add($x, $y){
    echo $x + $y;
}
function sub($x, $y){
    echo $x - $y;
}
$var = readline("enter name of function: ");
$var(10, 20);
?>
enter name of function: add
30

Variable Methods in Classes

The concept extends to class methods, allowing dynamic method calls ?

<?php
class MyClass{
    function welcome($name){
        echo "Welcome $name";
    }
}
$obj = new MyClass();
$method = "welcome";
$obj->$method("Amar");
?>
Welcome Amar

Variable Static Methods

Static methods can also be called using variable function syntax ?

<?php
class MyClass{
    static function welcome($name){
        echo "Welcome $name";
    }
}
$method = "welcome";
MyClass::$method("Amar");
?>
Welcome Amar

Key Points

Feature Syntax Use Case
Function $var() Dynamic function calls
Method $obj->$method() Dynamic method calls
Static Method Class::$method() Dynamic static calls

Conclusion

Variable functions provide powerful dynamic programming capabilities in PHP. They're essential for building flexible applications with callbacks, function tables, and runtime function selection while maintaining clean, readable code.

Updated on: 2026-03-15T09:16:35+05:30

11K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements