fork(1) download
  1. <?php
  2.  
  3. class User {}
  4. class Contact {}
  5.  
  6. class MyClass {
  7.  
  8. private $handler;
  9.  
  10. public function setHandler($function) {
  11. try {
  12. $r = new ReflectionFunction($function);
  13. } catch (ReflectionException $e) {
  14. throw new InvalidArgumentException('Invalid callback passed.');
  15. }
  16. if ($r->getNumberOfParameters() !== 2) {
  17. throw new InvalidArgumentException('The callback must have exactly 2 arguments.');
  18. }
  19. static $d = array('User', 'Contact');
  20. foreach ($r->getParameters() as $i => $p) {
  21. if (!$c = $p->getClass() or strcasecmp($c->getName(), $d[$i])) {
  22. throw new InvalidArgumentException(sprintf(
  23. 'The argument #%d must have type hinting: %s',
  24. $i + 1,
  25. $d[$i]
  26. ));
  27. }
  28. }
  29. $this->handler = $function;
  30. }
  31.  
  32. }
  33.  
  34. $my = new MyClass;
  35. try {
  36. echo "A\n";
  37. $my->setHandler(function (User $user, Contact $contact) {});
  38. echo "B\n";
  39. $my->setHandler(function (User $user, $contact) {});
  40. echo "C\n";
  41. } catch (Exception $e) {
  42. echo $e->getMessage();
  43. }
Success #stdin #stdout 0.01s 20568KB
stdin
Standard input is empty
stdout
A
B
The argument #2 must have type hinting: Contact