Skip to content

Instantly share code, notes, and snippets.

@y8r
Created May 13, 2015 18:02
Show Gist options
  • Save y8r/5251e876c877be664876 to your computer and use it in GitHub Desktop.
Save y8r/5251e876c877be664876 to your computer and use it in GitHub Desktop.
Calculator Class
<?php
/**
* Calculator Class
* @author Jeff Yates <hello+gist@jeffyates.com>
*/
class Calculator
{
public function __call($method, $args)
{
$methods = array(
'add' => '+',
'subtract' => '-',
'multiply' => '*',
'divide' => '/'
);
try {
if (array_key_exists($method, $methods) === false) {
throw new Exception("Invalid operation");
}
$calculate = implode($methods[$method], $args);
if ($method === 'divide' && preg_match('/0$/i', $calculate) === 1) {
throw new Exception("Division by zero");
}
return eval("return $calculate;");
} catch (Exception $e) {
return 0;
}
}
}
// Examples
$calc = new Calculator;
var_dump($calc->add(1,2,3,4,5));
var_dump($calc->subtract(5,4));
var_dump($calc->multiply(4,3,2));
var_dump($calc->divide(4,0));
var_dump($calc->divide(4,1));
var_dump($calc->add($calc->subtract(10,1), $calc->multiply(3,1)));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment