33

Is it possible to call functions from class like this:

$class = new class;
$function_name = "do_the_thing";
$req = $class->$function_name();

Something similar solution, this doesn't seem to work?

Martti Laine
  • 12,655
  • 22
  • 68
  • 102
  • possible duplicate of http://stackoverflow.com/questions/936875/how-would-i-call-a-method-from-a-class-with-a-variable – outis Apr 17 '10 at 06:49

4 Answers4

64

Yes, it is possible, that is know as variable functions, have a look at this.

Example from PHP's official site:

<?php
class Foo
{
    function Variable()
    {
        $name = 'Bar';
        $this->$name(); // This calls the Bar() method
    }

    function Bar()
    {
        echo "This is Bar";
    }
}

$foo = new Foo();
$funcname = "Variable";
$foo->$funcname();  // This calls $foo->Variable()

?>

In your case, make sure that the function do_the_thing exists. Also note that you are storing the return value of the function:

$req = $class->$function_name();

Try to see what the variable $req contains. For example this should give you info:

print_r($req); // or simple echo as per return value of your function

Note:

Variable functions won't work with language constructs such as echo(), print(), unset(), isset(), empty(), include(), require() and the like. Utilize wrapper functions to make use of any of these constructs as variable functions.

Sarfraz
  • 377,238
  • 77
  • 533
  • 578
8

My easiest example is:

$class = new class;
$function_name = "do_the_thing";
$req = $class->${$function_name}();

${$function_name} is the trick

Also works with static methods:

$req = $class::{$function_name}();
tivnet
  • 1,898
  • 17
  • 19
Tudor
  • 319
  • 5
  • 13
  • 2
    I get an error using $req = $class->${$function_name}(); However the following seems to be the correct syntax $req = $class->{$function_name}(); – Martin Jun 12 '15 at 09:13
  • thanks @Martin for the fix. I will need to check again with the code where it comes from to see why I had this error. – Tudor Jun 18 '15 at 14:58
  • 1
    Methods using variable variables, nice! – Wietse Nov 04 '15 at 10:10
0

Also try this (note the curly brackets {} ):

$class = new class;
$function_name = "do_the_thing";
$req = $class->{$function_name}();
ddanone
  • 464
  • 4
  • 8
-1

You can use ReflectionClass.

Example:

$functionName = 'myMethod';
$myClass = new MyClass();
$reflectionMyMethod = (new ReflectionClass($myClass))->getMethod($functionName);

$relectionMyMethod->invoke($myClass); // same as $myClass->myMethod();

Remember to catch ReflectionException If Method Not Exist.

user2986600
  • 1
  • 1
  • 2