-1

我正在尝试设置一个 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));
4

1 回答 1

1

这就是我的做法,正如我在评论中所说,您可以直接调用它而无需调用额外的函数调用

function testCallback($object, $method) {
   echo $method;
   if( !method_exists( $object, $method) ) throw new Exception( "Method does not exist ".$object::class.'::'.$method);
   echo $object->$method();
}

唯一使用的时间call_user_func*是当你有论点时(即使这样你也可以使用反射),比如这样。

function testCallback($object, $method, array $args = []) {
   echo $method;
   if( !method_exists( $object, $method) ) throw new Exception( "Method does not exist ".$object::class.'::'.$method);
   echo call_user_func_array( [$object,$method], $args);
}

或反射(可能有点慢)

function testCallback($object, $method, array $args = []) {
   echo $method;
   if( !method_exists( $object, $method) ) throw new Exception( "Method does not exist ".$object::class.'::'.$method);
   echo (new ReflectionMethod( $object, $method))->invokeArgs( $object, $args );
}
于 2017-08-12T03:01:39.253 回答