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?
PHP supports the concept of variable functions. This means that if a variable name has parentheses appended to it, PHP will look for a function with the same name as whatever the variable evaluates to, and will attempt to execute it.
Summary. Append parentheses () to a variable name to call the function whose name is the same as the variable's value. Use the $this->$variable() to call a method of a class. Use the className::$variable() to call a static method of a class.
Your accessing a variable inside the class. Inside the class you call methods and variables like so: $this->myMethod() and $this->myVar . Outside the Class call the method and var like so $test->myMethod() and $test->myVar . Note that both methods and variables can be defined as Private or Public.
If name of a variable has parentheses (with or without parameters in it) in front of it, PHP parser tries to find a function whose name corresponds to value of the variable and executes it. Such a function is called variable function. This feature is useful in implementing callbacks, function tables etc.
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.
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}();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With