我正在尝试设置一个 PHP 方法,该方法传递一个对象及其方法名称,然后调用该对象的该方法。我试图在我的代码中限制字符串的使用,所以我想使用自定义枚举来做到这一点。但是,当我运行此示例时,这是我收到的输出:
获取测试
警告 call_user_func() 期望参数 1 是有效的回调,第二个数组成员不是第 43 行的有效方法
echo call_user_func(array($object, $method));
虽然它似乎打印出正确的方法,但它表示正在传递的方法不是有效的方法。我很困惑,因为我按照 PHP.net 上的教程进行操作
http://php.net/manual/en/function.call-user-func.php
在类的方法上使用 call_user_func 的正确方法是什么?请让我知道我错过了什么/做错了什么?
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));