Vanilla 1.1.5a is a product of Lussumo. More Information: Documentation, Community Support.
I was working on an intranet application today, and I came across a situation where it would be very helpful to be able to define arithmetic operators for a custom object.
For instance, assume the following class definition:
class Test
{
public $member;
}
The code below shows what I would like to be able to do:
// Create the first test object.
$obj1 = new Test();
$obj1->member = 2;
// Create the second test object.
$obj2 = new Test();
$obj2->member = 6;
// Create the third test object as the sum of the first two.
$obj3 = $obj1 + $obj2;
// Print the "member" variable of the third test object.
echo($obj3->member); // Would print "8".Back in my college programming classes I used to write these methods (e.g. defining how the "+" operator worked when both operands were Test objects) all the time in C++, but I don't think I've ever seen it done in PHP. I know I could write constructor and helper methods to accomplish the same thing, but I prefer using the built in operators if possible. Another thing I'd like to be able to do is something like the following:
// Create the test object.
$obj = new Test();
$obj->member = 2;
// Add 6 to the test object.
$obj += 6;
// Print the "member" variable of the test object.
echo($obj->member); // Would print "8".Is this something that's possible and I've missed, or am I dreaming?
$obj = new Test();
$obj->member = 2;
$obj->member += 2;
echo $obj->member; // =4
class Test {
public $member = 0;
public function addMember($mem=0){
if((int)$mem>0) $this->member += $mem;
}
}
$obj = new Test;
$obj->member = 2;
$obj->addMember(4);
echo $obj->member; // =6
1 to 3 of 3