The problem is actually quite easy, but somewhat difficult to explain, but I'll do my best.
Assume the following function and class:
somethingsomething.php
function do_something($a, $b, $whatToDo) {
$value = someRandomClass::doThis();
return $a + $b * $value;
}
someRandomClass.class.php
class someRandomClass {
public static doThis() {
return $this->valueThis;
}
public static doThat() {
return $this->valueThat;
}
public static doSomethingElse() {
return $this->valueSomethingElse;
}
}
So, we have a function which does ... something. It gets 3 parameters:
$a
= An integer
$b
= Also an integer
$whatToDo
. = A string, either this
, that
or somethingElse
As you can see, the calculation in do_something()
requires a value which is received through one of the 3 functions in the class. But the function which is called should be defined by the value in $whatToDo
. Of course, i could create an if- or switch-statement which would look like this:
function do_something($a, $b, $whatToDo) {
if($whatToDo === "this") {
$value = someRandomClass::doThis();
} elseif ($whatToDo === "that") {
$value = someRandomClass::doThat();
} elseif ($whatToDo === "somethingElse") {
$value = someRandomClass::doSomethingElse();
}
return $a + $b * $value;
}
But this looks horrible and if I got more (the actual code can have up to 41 different "$whatToDo
's") it's really difficult to read.
I wonder if there is a way to use a variable to "create" a function name and call that function, so something like:
function do_something($a, $b, $whatToDo) {
$value = someRandomClass:: "do" . $whatToDo ."()";
return $a + $b * $value;
}
so that if $whatToDo
contains "this", it will call doThis()
.
Is that possible by any means necessary?