PHP - Write program to call dynamic method

Requirements

Write program to call dynamic method

It should implement the following methods via dynamic way:

  • pow() that returns the result of raising the first number (the base) to the power of the second number
  • sqrt() that returns the square root of the first number
  • exp() that returns e raised to the power of the first number

Hint

You can use the special __call() method to create the virtual "methods" pow(), sqrt(), and exp() that simply call their respective built-in math functions.

Demo

<?php
        class Calculator {
          protected $_val1, $_val2;

          public function __construct($val1, $val2) {
            $this->_val1 = $val1;//from w w w  .j a v  a  2  s  .c o  m
            $this->_val2 = $val2;
          }

          public function add() {
            return $this->_val1 + $this->_val2;
          }

          public function subtract() {
            return $this->_val1-$this->_val2;
          }

          public function multiply() {
            return $this->_val1 * $this->_val2;
          }

          public function divide() {
            return $this->_val1 / $this->_val2;
          }

          private static $_allowedFunctions = array("pow"=> 2,"sqrt"=> 1,"exp"=> 1);

          public function __call($methodName, $arguments) {
            if (in_array($methodName, array_keys($_allowedFunctions))) {
                  $functionArguments = array($this->_val1);
              if (CalcAdvanced::$_allowedFunctions[$methodName] == 2) array_push(
                  $functionArguments, $this->_val2);
              return call_user_func_array($methodName, $functionArguments);
            } else {
              die ("Method'CalcAdvanced::$methodName'doesn't exist");
            }
          }
        }

        $ca = new Calculator(3, 4);
        echo "3 + 4 =". $ca->add()."\n";
        echo "3-4 =". $ca->subtract()."\n";
        echo "3 * 4 =". $ca->multiply()."\n";
        echo "3 / 4 =". $ca->divide()."\n";
        echo "pow(3, 4) =". $ca->pow()."\n";
        echo "sqrt(3) =". $ca->sqrt()."\n";
        echo "exp(3) =". $ca->exp()."\n";

?>

Result

Related Exercise