1

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

1
  • What problem are you trying to solve? There is probably a better way. Commented Nov 26, 2012 at 18:31

5 Answers 5

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

+1 call_user_func makes it explicit what you're trying to do in your code ... which is much better for poor Joe Programmer who has to maintain it down the road and doesn't inappropriately expose you to the dangers of eval.
1

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 Comment

Wow! it is great way to do it :)
1
  1. Use eval.
  2. You almost never ever ever should do this. There's almost always a better, safer, more secure way.

1 Comment

@MadaraUchiha Hence the "don't do this" note.
0

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

Comments

0

A suggestion with a fail safe:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.