-2

Given MyCalculator class

class MyCalculator
{
    public float $a, $b, $c, 
    public MyCalculator $result;
            
    public function __construct ($a, $b)
    {
        $this->a = $a;
        $this->b = $b;
        
        $this->result = new MyCalculator($this->c, 0)
    }

    public function add()
    { 
        $this->result->c = $this->a + $this->b;
        return $this->result->c;
    }

    public function divideBy($num)
    { 
        $this->result->c = $this->result->c / $num;
        return $this->result->c;
    }
}

$calc = new MyCalculator(12, 6);

In my code works good either:

echo $calc->Add()  // Displays: 15

or

echo $calc->Add()->DivideBy(3)   // Displays: 5  ((6+9)/3=5)

But I cannot make them working both!

Max
  • 3
  • 4
  • 2
    Show your MyCalculator class – aynber Feb 15 '23 at 18:42
  • Cannot answer your question, because it is closed. But [here is an example](https://3v4l.org/CeIQY) of how your calculator could work. Although I think [the magic __toString() method](https://3v4l.org/Htvu2) proposed by Sammitch is a good idea, it might just be a bit too magical and I therefore chose a normal method instead. – KIKO Software Feb 16 '23 at 08:50

1 Answers1

-1

Based on the description of your problem, you will want to setup this class definition:

class MyCalculator
{
    private $value1;
    private $value2;
    public $total;

    public function __construct($value1, $value2, $total = null)
    {
        $this->value1 = $value1;
        $this->value2 = $value2;
        $this->total = $total;
    }

    public function add()
    {
        $this->total = $this->value1 + $this->value2;
        return new MyCalculator(0, 0, $this->total);
    }

    public function divideBy($value)
    {
        return $this->total / $value;
    }
}

What this does is set two required property values and one optional property value in the constructor, create an add method that returns a new instance of the class where the total matches the sum of the two values passed in the constructor, and creates a divideBy method that divides the current total by the desired number.

Here is an example of using it:

$calc = new MyCalculator(6, 9);
echo $calc->add()->divideBy(3);

Fiddle: https://onlinephp.io/c/498ed

David
  • 5,877
  • 3
  • 23
  • 40