How do I overload arithmetic operators

In PHP, you can overload arithmetic operators by using the magic methods. This allows you to define how operators like +, -, *, and / behave with your custom classes. Below is an example demonstrating how to overload the addition operator.

<?php class Vector { public $x; public $y; public function __construct($x, $y) { $this->x = $x; $this->y = $y; } public function __toString() { return "($this->x, $this->y)"; } public function __add($v) { return new Vector($this->x + $v->x, $this->y + $v->y); } } $v1 = new Vector(1, 2); $v2 = new Vector(3, 4); $v3 = $v1 + $v2; echo $v3; // Outputs: (4, 6) ?>

PHP operator overloading arithmetic operators magic methods custom classes