0

I put my question in the following code since it seems the easier way how to explain my question:

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.
       }
}

Reflection seems so impractical for daily use. How would you solve the problem?

3
  • With PHP, some compromise is necessary. PHP is a dynamic typing language. You should learn static typing language, such as Java, Scala or Haskell.
    – mpyw
    Jun 14, 2014 at 12:57
  • I've programmed in many languages (both static and dynamic). And I know what you are saying but since I want to eliminate possible bugs from my PHP code it is not much of a help.
    – MartyIX
    Jun 14, 2014 at 13:11
  • I'm just curious how other people approach this problem.
    – MartyIX
    Jun 14, 2014 at 13:12

2 Answers 2

1

It seems like you want to confirm that a given callback function does have a certain interface.

Functions cannot implement interfaces, but classes can. Why don't you pass an object implementing a certain interface instead of a function?

1
  • Yes, I can work around the issue with an interface. However, is it what you do in your code?
    – MartyIX
    Jun 14, 2014 at 13:59
0

Do you really think this snippet has heavy weight...? I don't think so.

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;
    }

}

Example: http://ideone.com/kt7jk7
Benchmark: http://ideone.com/OmF010

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.