Dispatcher - PHP Online

Form of PHP Sandbox

Enter Your PHP code here for testing/debugging in the Online PHP Sandbox. As in the usual PHP files, you can also add HTML, but do not forget to add the tag <?php in the places where the PHP script should be executed.



Your result can be seen below.

Result of php executing





Full code of Dispatcher.php

  1. <?php
  2.  
  3. class Dispatcher
  4. {
  5.     private $events;
  6.     
  7.     public function addEvent(string $event, Closure $closure): void
  8.     {
  9.             $this->events[$event][] = $closure;
  10.     }
  11.     
  12.     public function trigger(string $event, $args): void
  13.     {
  14.         foreach ($this->events[$event] as $func) {
  15.             call_user_func($func, $args);
  16.         }
  17.     }
  18. }
  19.  
  20. $dispatcher = new Dispatcher();
  21.  
  22. $dispatcher->addEvent('show', function($string) {
  23.     echo 'Show first event ' . $string . PHP_EOL;
  24. });
  25.  
  26. $dispatcher->addEvent('show_another', function($string) {
  27.     echo 'Show second event ' . $string . PHP_EOL;
  28. });
  29.  
  30. $dispatcher->trigger('show', 'Astound');
  31. $dispatcher->trigger('show_another', 'Astound');
  32.  
File Description
  • Dispatcher
  • PHP Code
  • 30 Aug-2019
  • 701 Bytes
You can Share it: