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

To call a function from a string stored in a variable in PHP, you can use the call_user_func() function. Here is an example:

<?php

$function_name = 'some_function';

if (function_exists($function_name)) {
  if (call_user_func($function_name)) {
    echo "Function $function_name called successfully.";
  } else {
    echo "Failed to call function $function_name.";
  }
} else {
  echo "Function $function_name does not exist.";
}

In the example above, some_function is the name of the function stored in the string variable $function_name. The function_exists() function is used to check if the function exists before calling it, to avoid errors.

Watch a course Learn object oriented PHP

Alternatively, you can also use the call_user_func_array() function to call a function and pass an array of arguments to it. Here is an example:

<?php

function some_function()
{
  echo "Hello, world!";
}

$function_name = 'some_function';
$arguments = [1, 2, 3];

if (function_exists($function_name)) {
  call_user_func_array($function_name, $arguments);
}

This would output:/p>

Hello, world!