Current Location: Home> Latest Articles> How to Implement Basic Arithmetic Operations with a PHP Class

How to Implement Basic Arithmetic Operations with a PHP Class

gitbox 2025-06-29

Introduction

In web development, basic mathematical operations such as addition, subtraction, multiplication, and division are frequently needed. To avoid writing similar code multiple times, this article introduces how to use a PHP class to perform arithmetic operations between two numbers, enhancing code reusability and readability.

Implementing the PHP Class

To perform basic arithmetic operations, we can create a PHP class with four properties: two operands ($a, $b), an operator ($operator), and a result ($result). Different methods in this class can then be defined to handle the operations.

First, we define a constructor method to initialize the class properties:

class Calculator {
    protected $a;
    protected $b;
    protected $operator;
    protected $result;

    public function __construct($a, $b, $operator) {
        $this->a = $a;
        $this->b = $b;
        $this->operator = $operator;
        $this->result = null;
    }
}

In the constructor, $a and $b are the two operands, $operator is the arithmetic operator, and $result is initialized to null.

Implementing the Calculation Method

Next, we define a method called calculate() that performs the corresponding operation based on the given operator. Here's the implementation:

public function calculate() {
    switch($this->operator) {
        case '+':
            $this->result = $this->a + $this->b;
            break;
        case '-':
            $this->result = $this->a - $this->b;
            break;
        case '*':
            $this->result = $this->a * $this->b;
            break;
        case '/':
            if($this->b == 0) {
                throw new Exception('Division by zero is not allowed');
            } else {
                $this->result = $this->a / $this->b;
            }
            break;
        default:
            throw new Exception('Invalid operator');
    }
    return $this->result;
}

This method uses a switch statement to perform different operations based on the operator. If the operator is division and the divisor is zero, an exception is thrown.

Example Usage

Using this class for calculations is straightforward. Simply instantiate the class and call the calculate() method. Here's an example for addition:

$calc = new Calculator(2, 3, '+');
echo $calc->calculate();

Conclusion

Through the method introduced in this article, you can easily implement basic arithmetic operations between two numbers. Using a PHP class to encapsulate the calculation logic improves both the readability and reusability of your code. In real-world development, you can also extend this class by inheriting and overriding the calculate() method to handle more complex calculations.