1

I have a rather stupid PHP question :D! I would like to simplify the following statement:

function hello_input() {
    return 'Hello World';
}

$helper = 'hello';

$helper = $helper . '_input';

$data = $helperinput();

The specific part I want to simplify is the adding of the _input to the $helper so it calls the right function.

I thought of something like this but it doesn't work:

$data = $helper. 'input'();
or
$data = $helper. 'input' . ();

Any ideas?

Thanks, Max

1
  • I really would like to know why you would want to simplify anything here? Sure you can write the same code that you need 2 lines for in 1 line, but seriously: does it matter? I'd call that premature optimization. Commented Sep 14, 2009 at 20:59

4 Answers 4

13

Use call_user_func, e.g. $data = call_user_func($helper.'input');.

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

Comments

0
$helper = 'hello_';
$data = $helper.'input';
call_user_func($data);

That should get you most of the way there. Good luck!

Docs here

Comments

0

Are you expecting to invoke code based on an input? You should never try to do that. That gives people the chance to execute arbitrary code. Even if you can't see quite how, it's still a potential method of attack.

What you probably want is a switch statement (or chained if statements) that match an input and dispatch the correct function.

3 Comments

Not arbitrary code, just funtcions in a special namespace that are designed to be called from outside. Saying this is insecure, is like saying that it's insecure to let the visitor of your site choose which php file to execute.
If they're in a special namespace, fine. But I would still say that this hints at a less-than-optimal design. Reflection (and its analogues) don't belong production code. In my opinion.
Hey thanks for pointing that out however this is for an API and you can only make calls with several different functions (I mean if the function doesn't exist there is nothing you can do). As in "plugins"...and in the POST only defined values are allowed...
0

Get the whole function name into a string first.

$helper = 'hello';
$func = $helper . '_input';
$data = $func();

PHP calls this variable functions. See also variable variables.

3 Comments

It's what his first code sample does (although variable name is wrong, but I assume that's mistake left by $helper. 'input'();-like experiments). And he asks how to simplify it.
I made no such assumption about his example. My answer is the corrected syntax of his two non-working attempts at the bottom of his question.
Nice. Got somebody following you around, upvoting you and downvoting me?

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.