fork download
  1. <?php
  2.  
  3. class FunctionHolder
  4. {
  5.  
  6. private $functions;
  7.  
  8. public function __construct()
  9. {
  10. $this->functions = [];
  11. }
  12.  
  13. /**
  14.   * @param callable $function
  15.   * @param string $functionName
  16.   * @throws Exception
  17.   */
  18. public function registerFunction($function, $functionName)
  19. {
  20. if (!is_callable($function)) {
  21. throw new Exception ('Not a function');
  22. }
  23. $this->functions[$functionName] = $function;
  24. }
  25.  
  26. /**
  27.   * @param string $functionName
  28.   * @param array $parameters
  29.   */
  30. public function run($functionName, $parameters)
  31. {
  32. call_user_func_array($this->functions[$functionName], $parameters);
  33. }
  34.  
  35. public function __call($functionName, $parameters)
  36. {
  37. if (isset($this->functions[$functionName])) {
  38. call_user_func_array($this->functions[$functionName], $parameters);
  39. } else {
  40. throw new Exception ("method $functionName not found in " . __CLASS__);
  41. }
  42. }
  43. }
  44.  
  45. $functionHolder = new FunctionHolder();
  46. /**
  47.  * @param int $number
  48.  * @param string $string
  49.  */
  50. $function = function ($number, $string) {
  51. echo "Номер $number";
  52. echo "\nСтрока $string";
  53. };
  54. $functionHolder->registerFunction($function, 'printNumbers');
  55. //$functionHolder->run('printNumbers', [12, 'попугай']);
  56. $functionHolder->printNumbers(12, 'попугай');
  57.  
  58. try {
  59. $functionHolder->printNumbersTwo(12, 'попугай');
  60. } catch (Exception $e) {
  61. echo PHP_EOL . $e->getMessage() . PHP_EOL;
  62. }
  63.  
Success #stdin #stdout 0.02s 52472KB
stdin
Standard input is empty
stdout
Номер 12
Строка попугай
method printNumbersTwo not found in FunctionHolder