I am trying to setup a PHP method that gets passed an object and its method name, then gets calls that method of the object. I am trying to limit the usage of strings in my code, so I would like to do it using a custom enum. When I run this example though, this is the output I receive:
getTest
WARNING call_user_func() expects parameter 1 to be a valid callback, second array member is not a valid method on line number 43
echo call_user_func(array($object, $method));
Although it seems to print out the correct method, it says the method being passed isn't a valid method. I'm confused because I followed the tutorial on PHP.net
http://php.net/manual/en/function.call-user-func.php
What is the proper way to use call_user_func on a class's method? Please let me what I am missing/doing wrong?
abstract class MyEnum
{
final public function __construct($value)
{
$c = new ReflectionClass($this);
if(!in_array($value, $c->getConstants())) {
throw IllegalArgumentException();
}
$this->value = $value;
}
final public function __toString()
{
return $this->value;
}
}
class one {
private $test = 1;
public function getTest() {
return $this->test;
}
}
class two {
private $quiz = 2;
public function getQuiz() {
return $this->quiz;
}
}
class Number extends MyEnum {
const ONE = "getTest";
const TWO = "getQuiz";
}
function testCallback($object, $method) {
echo $method;
echo call_user_func(array($object, $method));
}
$temp1 = new one();
$temp2 = new two();
testCallback($temp1, new Number(Number::ONE));