Page 1 of 1

Question about constructing a function call differently

Posted: Fri Nov 26, 2010 8:47 am
by thedanny09
Hey Guys

So here's the issue I'm having, hopefully someone can help me out with it.

I have a function, lets call it LoadData(), its a function inside a class, the name doesn't matter.

The purpose of this function is call some getters, and create an object and a function call, based on the returned values.

My issue is, i cant seem to get the function call part to work.

Here's some assumptions.

$foo is a variable holding an object, assume its been instantiated, so if we were to type manually $foo->func_name(); it would work correctly.

My issue is, func_name is inside a variable called $myFunc; if you echo that it will show you func_name() on the screen, with the parenthesis included.

I am trying to do $foo->$myFunc; but it doesnt seem to be going into the function, whereas if i do $foo->func_name(); it will.

Im doing this because the user is inputting the object he wants, and the method inside that object to call.

If anyone can give me some insight on how to do this; dont worry about passing anything to the function assume it is void.

I've been doing PHP for about 4 years now, I'm definitly not a novice, but im not a pro, not yet that is. So go technical on the explanation if you want, im here to learn.

Thanks to anyone for the help!!!

Re: Question about constructing a function call differently

Posted: Fri Nov 26, 2010 9:52 am
by pickle
So the user inputs "foo" and "func_name" and you want to turn that into, essentially, $foo->func_name?

First off - let me say this is very dangerous & I hope you're running "foo" through a whitelist to ensure users can only enter/choose certain classes.

Second, to answer your question - you can use variable variables for this.

Code: Select all

$class = $_POST['user_entered_class_name'];//you should clean this user input, but I'm not bothering for this example
$func = $_POST['user_entered_function'];

${$class}->$func()
//If that doesn't work, try
${$class}->{$func}()

Re: Question about constructing a function call differently

Posted: Fri Nov 26, 2010 9:56 am
by Weirdan

Code: Select all

$params = array(1, "second", $third);
$methodName = "doSomething"; // It should contain ONLY the method name (no parenthesis, no spaces, no semicolons, etc).
$methodReturn = call_user_func_array(array($foo, $methodName), $params);