Calculator in PHP

To develop a simple calculator class in the context of PHP is more fun with __call() magic method.

class Calculator {
    public function __call($method, $args) {
        if (isset($this->$method)) {
            $func = $this->$method;
            return call_user_func_array($func, $args);
        }
    }
}

$calculator = new Calculator();
$calculator->add = function ( $a1, $a2 ) { echo $a1 + $a2; };
$calculator->subs = function( $a1, $a2 ) { echo $a1 - $a2; };
$calculator->multi = function( $a1, $a2 ) { echo $a1 * $a2; };
$calculator->div = function( $a1, $a2 ) { echo $a1 / $a2; };

Leave a Reply

Your email address will not be published. Required fields are marked *