Created
April 25, 2010 03:26
-
-
Save sotarok/378134 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| if ($argc <= 3) { | |
| echo <<<EOI | |
| Usage: | |
| % php {$argv[0]} operator arg1 arg2 [arg3 ...] | |
| operator + or - or * or / | |
| arg integer | |
| EOI; | |
| exit; | |
| } | |
| $op = $argv[1]; | |
| $params = array_slice($argv, 2); | |
| $ops = function ($op) | |
| { | |
| $operators = array( | |
| '+' => function ($v1, $v2) { return $v1 + $v2; }, | |
| '-' => function ($v1, $v2) { return $v1 - $v2; }, | |
| '*' => function ($v1, $v2) { return $v1 * $v2; }, | |
| '/' => function ($v1, $v2) { if ($v2 === 0) throw new Exception('Zero division error'); return $v1 / $v2; }, | |
| ); | |
| if (!isset($operators[$op])) { | |
| throw new Exception('Invalid operator: operator is +, -, * or /'); | |
| } | |
| $func = $operators[$op]; | |
| return function () use (&$func) { | |
| $args = func_get_args(); | |
| $total = array_shift($args); | |
| foreach ($args as $arg) { | |
| $total = call_user_func($func, $total, (int)$arg); | |
| } | |
| return $total; | |
| }; | |
| }; | |
| try { | |
| echo call_user_func_array($ops($op), $params), PHP_EOL; | |
| } catch (Exception $e) { | |
| echo $e->getMessage(), PHP_EOL; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment