如何让php函数作为字符串做实函数?

lets assume that i have function named printuser()

now if i have string like

$myFunction = 'printuser()';

how i can run this string as function ? so it should do the printuser() function

If you just want $myFunction to specify which function to run, you can do something like

$myFunction = 'printuser';
$myFunction();

This is called a "variable function", and is slightly less dangerous than eval. (You can call any existing function, but you can't run arbitrary code.)

Be warned, though: if printuser doesn't exist, the script will die. You might consider checking for the function's existence before calling it.

$myFunction = 'printuser';
if (function_exists($myFunction))
    $myFunction();
else
    throw new BadFunctionCallException("Function '$myFunction' doesn't exist");

Replace the throw with whatever you want to do if the function isn't there. That's just an example.

  1. Use eval.
  2. You almost never ever ever should do this. There's almost always a better, safer, more secure way.

Have a look at call_user_func. You'll need to change your string a little (no brackets).

You can try

$myFunction = 'printuser()';
# Remove brakets
$myFunction = rtrim($myFunction, "()");
# Call Function Directly
$myFunction();

For validation you can use is_callable

is_callable($myFunction) and $myFunction();

Simple Demo

A suggestion with a fail safe:

$function = str_replace("()", "", $input);
if( function_exists($function))
{
  $function();
}
else
{
  // ignore or show an error
}