Jump to content

How does one overload Arithmetic operators for a class?


Fligex

Recommended Posts

self points to the current class, so basically it says function add(A $b). You'll see also other like static. However this won't work, since static is late bind, while self is early bind which is why this works.

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.

Not quite. ignace is using type hinting, which means that only a value of the specified type can be passed to that method. In this case self resolves to the class name of which it is used in, or, A. So he is saying that only a value of type A can be passed to that method.

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.