Jump to content

Recommended Posts

PHP does not support arithmetic operator overloading. You can however use a simple method to achieve this.

 

class A {
  public $value;
  function add(self $b) {
    $this->value += $b->value;
  }
}
Edited by ignace

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.

Edited by ignace
  • Like 1

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