0

I keep getting an error that says function name must be in a string or it simply runs but doesn't print either string in the function. What am I missing?

<?php

$funName="{'$oneRun()'}";
echo "Hello You are running ".$funName."\n\n$";

function oneRun()
{ echo "Running Function One";return "one";}

function twoRun()
{ echo "Leave me alone, go bug Function One";return "two";}

?>
  • possible duplicate of [How to call PHP function from string stored in a Variable](http://stackoverflow.com/questions/1005857/how-to-call-php-function-from-string-stored-in-a-variable) – BlitZ Feb 28 '14 at 16:33

3 Answers3

3

You mean callables or variable functions?

$funName = 'oneRun'; // save only name

echo "Hello You are running " . $funName() . "\n\n$";
BlitZ
  • 12,038
  • 3
  • 49
  • 68
  • PERFECT! Thanks, I was making it too complex! – Firehawk573 Feb 28 '14 at 16:26
  • @Firehawk573 Welcome to SO. Take a [tour](http://stackoverflow.com/tour). Search similar [questions](http://stackoverflow.com/questions/1005857/how-to-call-php-function-from-string-stored-in-a-variable). Accept answers. – BlitZ Feb 28 '14 at 16:33
0

You are calling an echo in another echo, that couldn't work.

I guess something like :

<?php

$funName="{'$oneRun()'}";
echo "Hello You are running ";
oneRun();
echo "\n\n$";

function oneRun()
{ echo "Running Function One";return "one";}

function twoRun()
{ echo "Leave me alone, go bug Function One";return "two";}

?>

Would do the job ?

enguerranws
  • 8,087
  • 8
  • 49
  • 97
0

I always use:

call_user_func($string_function_or_closure, ...);
call_user_func(array($object, 'Method'), ...);
call_user_func(array(StaticClass, 'Method'), ...);

or:

call_user_func_array($string_function_or_closure, array(...));
call_user_func_array(array($object, 'Method'), array(...));
call_user_func_array(array(StaticClass, 'Method'), array(...));

for string functions. It's a bit more explicit than:

$function();

and it also makes it better visible in your IDE.

CodeAngry
  • 12,760
  • 3
  • 50
  • 57