Jump to content

How does one overload Arithmetic operators for a class?


Fligex

Recommended Posts

Thanks for the extra info ignace, I had guessed self was referencing the current class some how but I'm curious what it is actually doing.. "granted I know this syntax is wrong" but I imagine its something like this:

function add(new thisClass($b))

Is that an accurate depiction of what is happening? Btw I didn't end up using the keyword since I wasn't sure what it was doing and I wanted to include more parameters.

Link to comment
Share on other sites

Like scootsah already pointed out, you can only pass instances of A. That said to make it more natural to arithmetic operations you can use value objects.

 

class Operand {
  private $value;
  public function __construct($val) { $this->value = $val; }
  public function add(self $other) {
    return new static($this->value + $other->value);
  }
  public function __toString() {
    return $this->value;
  }
}
So your program can look like this:

 

$seven = new Operand(7);
$four = new Operand(4);

$eleven = $seven->add($four);

var_dump($seven, $four, $eleven);

$twentytwo = $eleven->add($seven)->add($four);

var_dump($seven, $four, $eleven, $twentytwo);
As you can see $seven remains the value 7 as does $four remain the value 4 throughout the application.
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.