How to call a function from a string stored in a variable PHP?

In PHP, you can call a function from a string stored in a variable by simply using the variable as if it were the function name. This technique is known as variable functions and allows for dynamic function calls at runtime.

Syntax

The basic syntax for calling a function from a string is ?

$functionName = 'myFunction';
$functionName(); // Calls myFunction()

Example

Here's a complete example demonstrating how to call different functions dynamically ?

<?php
function hello() {
    echo "Calling hello method.<br>";
}

function welcome() {
    echo "Calling welcome method.<br>";
}

// Call function using string variable
$func = 'hello';
$func();

// Call different function
$func = 'welcome';
$func();
?>
Calling hello method.
Calling welcome method.

Passing Parameters

You can also pass parameters to functions called from string variables ?

<?php
function greet($name) {
    echo "Hello, " . $name . "!<br>";
}

function calculate($a, $b) {
    echo "Sum: " . ($a + $b) . "<br>";
}

$func = 'greet';
$func('John');

$func = 'calculate';
$func(5, 3);
?>
Hello, John!
Sum: 8

Safety Check

Always verify that the function exists before calling it to avoid errors ?

<?php
function testFunction() {
    echo "Function exists and called successfully!";
}

$func = 'testFunction';

if (function_exists($func)) {
    $func();
} else {
    echo "Function does not exist.";
}
?>
Function exists and called successfully!

Conclusion

Variable functions in PHP provide a powerful way to call functions dynamically using string variables. Always use function_exists() to verify the function exists before calling it to prevent runtime errors.

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

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements