如何"验证"回调函数?

时间:2014-06-14 12:11:25

标签: php callback

我在下面的代码中提出了我的问题,因为它似乎更容易解释我的问题:

class MyClass 
{

       public function setHandler($function) {
             // at this point I would like to validate
             // that the function $function can be called
             // with certain parameters.
             //
             // For example: $function has to be a function
             // with the synopsis: function (User $user, Contact $contact) {}

             // The point of the check is to know about an error soon.
       }
}

反思对于日常使用来说似乎是不切实际的。你会如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

您似乎想要确认给定的回调函数是否确实具有某个接口。

函数不能实现接口,但类可以。为什么不传递实现某个接口而不是函数的对象?

答案 1 :(得分:0)

你真的认为这个片段有重量......?我不这么认为。

class MyClass {

    private $handler;

    public function setHandler($function) {
        try {
            $r = new ReflectionFunction($function);
        } catch (ReflectionException $e) {
            throw new InvalidArgumentException('Invalid callback passed.');
        }
        if ($r->getNumberOfParameters() !== 2) {
            throw new InvalidArgumentException('The callback must have exactly 2 arguments.');
        }
        static $d = array('User', 'Contact');
        foreach ($r->getParameters() as $i => $p) {
            if (!$c = $p->getClass() or strcasecmp($c->getName(), $d[$i])) {
                throw new InvalidArgumentException(sprintf(
                    'The argument #%d must have type hinting: %s',
                    $i + 1,
                    $d[$i]
                ));
            }
        }
        $this->handler = $function;
    }

}

示例:http://ideone.com/kt7jk7
基准:http://ideone.com/OmF010