How can I execute a PHP function when its name is stored as a string?

Solution 1:

You can use call_user_func() to call a function dynamically:
👉 PHP Manual – call_user_func()


// Call a function by its name
echo call_user_func('time'); // works with native functions

// Example with arguments
function greet($name) {
    return "Hello, $name!";
}

echo call_user_func('greet', 'Ashish'); 
// Output: Hello, Ashish!

Key Points:

The first argument is a string with the function name.

The second argument (and beyond) are the parameters passed to that function.

Works with user-defined functions and built-in functions (e.g., time()).

✅ This is useful when the function name is stored in a variable or comes from a dynamic source.

Solution 2:

You can call a function directly using a variable containing the function name, and pass arguments as usual:


<?php
$func = 'strtoupper';

$res = $func('i am uppercase');

echo $res; // Output: I AM UPPERCASE
?>

👉 This works because PHP supports variable functions (where a variable name can be used as a function call).

Notes & Best Practices:

✅ You can use both built-in functions (strtoupper, time, etc.) and user-defined functions.

🔍 To avoid errors, check if the function exists before calling it:


if (function_exists($func)) {
    echo $func('safe call');
}

⚙️ If you need to inspect how many parameters a function accepts, you can use Reflection:


$ref = new ReflectionFunction($func);
echo $ref->getNumberOfParameters();

👉 This approach is simpler than call_user_func() for direct calls but has less flexibility when working with variable argument lists.

Would you like me to show a side-