w3resource

PHP calculator class: Perform Arithmetic operations


16. Calculator Class with Private Result

Write a PHP class called 'Calculator' that has a private property called 'result'. Implement methods to perform basic arithmetic operations like addition and subtraction.

Sample Solution:

PHP Code :

<?php
class Calculator {
    private $result;

    public function __construct() {
        $this->result = 0;
    }

    public function getResult() {
        return $this->result;
    }

    public function add($number) {
        $this->result += $number;
    }

    public function subtract($number) {
        $this->result -= $number;
    }
}

$calculator = new Calculator();

$calculator->add(4);
$calculator->add(5);
$calculator->subtract(3);

$result = $calculator->getResult();
echo "Result: " . $result;
?>

Sample Output:

Result: 6

Explanation:

In the above exercise -

  • The "Calculator" class has a private property $result, which is initially set to 0 in the constructor method __construct().
  • The getResult() method retrieves the current value of the $result property.
  • The add($number) method takes a number as a parameter and adds it to the current value of $result.
  • The subtract($number) method takes a number as a parameter and subtracts it from the current value of $result.

Flowchart:

Flowchart: PHP class for file operations.

For more Practice: Solve these Related Problems:

  • Write a PHP class Calculator with a private result property and methods for addition and subtraction that update this property.
  • Write a PHP script to perform a series of calculations using a Calculator object and then display the final result through a getter method.
  • Write a PHP function to simulate a chain of arithmetic operations using a Calculator class, ensuring proper encapsulation of the result.
  • Write a PHP program to extend the Calculator class to include multiplication and division while maintaining private state and error checking.

Go to:


PREV : File Class with Total Size Calculation.
NEXT : ShoppingCart Class.

PHP Code Editor:



Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.