1

Is there a PHP function or command that runs a function based on a string, array, or similar? Basically, if the string "time" is passed, I want time() to be returned. Ideally, I'd like this to also support passed parameters. I just want this to be for individual functions, though. I DON'T want to eval() an entire block of code, for obvious reasons.

Does anything like this exist--or, preferably--is it native in PHP?

2 Answers 2

3

You can call a function using a variable containing the function name as well as pass any parameters to that function. Try:

<?php

$func = 'strtoupper';

$res = $func('i am uppercase');

echo $res; // I AM UPPERCASE

See variable functions and variable variables as well. As mentioned, call_user_func() works too.

For safety, you can call:

if (function_exists($func)) { ... }

before calling the function based to make sure you avoid errors. You can use ReflectionFunctionAbstract::getNumberOfParameters to determine the number of parameters the function accepts as well.

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

1 Comment

Hmm, interesting! I never knew about this. Thanks for the idea! Though the other answer answers the question better, I may end up using this instead, so +1 to you!
2

Try call_user_func() http://php.net/manual/en/function.call-user-func.php

The first argument is a string representing the function name. The second argument can be a single argument, or an array of arguments.

Edit:

It will even support native functions like time(), as you asked. Try it out like so:

echo call_user_func( 'time' );

2 Comments

Ahh, this looks like it's what I'm looking for! Thanks! Before I accept your answer, though, does it only support defined functions? Or are all functions (such as time()) supported?
It definitely does support all functions!

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.