-1

Is there a way to call dynamic functions in php. For an example lets guess I have a variable like below.

$myVar = 'my_test_function';

And I have a function named myTestFunction(). Is there a way to call the mentioned function using the $myVar variable's value? How to structure that variable as myTestFunction and call the mentioned function using that variable

i am batman
  • 581
  • 3
  • 6
  • 21

2 Answers2

2

Just do the following:

lcfirst(str_replace('_', '', ucwords($myVar, '_')))();
Samuil Banti
  • 1,735
  • 1
  • 15
  • 26
2

convert your string to function name first:

$myVar = 'my_test_function';
echo $myVar = str_replace('_', '', ucwords($myVar, '_')); //output myTestFunction
$myVar();
Chetan Ameta
  • 7,696
  • 3
  • 29
  • 44
  • 4
    As function names are case insensitive, you could just replace the underscores and be done with it. – Yoshi Nov 09 '17 at 11:49
  • 1
    @Yoshi yes you are right, but its good practice to have strict code techniques for future use. – Chetan Ameta Nov 09 '17 at 11:53
  • True, but I don't see the relevance here. It just adds overhead on the processing side, and if the stored name is never used (e.g. logging) it serves no real purpose. – Yoshi Nov 09 '17 at 12:02