Defining mathematical operator for classes

83 views Asked by At

Is (mathematical) operator overloading possible for PHP objects just like Python? I think the answer is no since I searched a lot and found nothing. Just want to confirm.

I have defined classes for (vectors) points and I want them to add up like numbers (their corresponding coordinates) and also to be basic operation like scalar product. Currently I have define it as follows

public function multiply($x){
    $this->X -= $x*$this->X;
    $this->Y -= $x*$this->Y;
}

public function divide($x){
    if (abs($x) < 10^-6){
        die("Scalar is less than 10e-6.");
    }
    $this->X = $this->X/$x;
    $this->Y = $this->Y/$x;
}

public function dot($point){
    return (sqrt($this->X*$point->X + $this->Y*$point->Y));
}

And for current implements, I am doing like this $vec1->add($vec2). I rather want it like this $vec3 = $vec1 + $vec2.

1

There are 1 answers

0
Anders On BEST ANSWER

I don't think it's in core, but there is a package called Operator that will do it for you. It's available here.