1

I know that if I have a function in PHP named "foo", I can call it dynamically in the following way:

$var = "foo";
$var();

And if foo is a method to an object named "bar", I can call it dynamically as follows:

$var = "foo";
$bar->$var();

The only problem here --- I need to dymaically specify not only the method of the object -- but I need to dynamically specify the object itself as well --- and pass the combination off to a library that utilizes the string convention for dynamic functions. Is there a way to do this?

Sophia_ES
  • 1,193
  • 3
  • 12
  • 22

2 Answers2

2

Very similar way to what you've done with the method name, you can specify the name of the class and call the constructor on the object:

$objectVar = 'myObject';
$bar = new $objectVar();
$objectVar = 'newObject';
$newBar = new $objectVar();

That will give you one object each of the myObject, and newObject class.

Reisclef
  • 2,056
  • 1
  • 22
  • 25
1

Or, if you want to specify the object and not to init a one new, you can use

$var = "objectName";
$func = "functionName";
$$var->$func();
Richard
  • 2,840
  • 3
  • 25
  • 37
  • Yes, I should have specified that, thanks for clarifying my post (and thanks for the upvote, this is my first public comment!) – Reisclef May 06 '15 at 06:23
  • One problem with this suggestion ---- I am not able to pass it to a library that expects the provided argument to be just one string that represents a function. To do that, I would have to have the whole object/method combination specified in _one string --- which your suggestion does not provide. I need to store _both_ in a string called $func that can be called as: $func() --- not as $$func(), not as $$fu->$nc() -- but as $func(), nothing more and nothing less. – Sophia_ES May 06 '15 at 19:20
  • @Sophia_ES: I do not know what you exactly mean, but you should have the complete object/function name in the variable. – Richard May 07 '15 at 05:57
  • @RichardReiber --- Maybe an example of what I am trying to do could help. Could you explain me how to use this suggestion to pass this a method of the current object as an event-handler to PHP Expat? – Sophia_ES May 07 '15 at 23:16
  • Have you a event-handler register method for this? – Richard May 08 '15 at 12:38