Not signed in (Sign In)

SkillShare - A place to discuss Web Standards and Web Design topics

Categories

Vanilla 1.1.5a is a product of Lussumo. More Information: Documentation, Community Support.

    • CommentAuthorvarland
    • CommentTimeDec 12th 2006
     permalink

    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?

    • CommentAuthorvarland
    • CommentTimeDec 12th 2006
     permalink
    It looks like this isn't possible, so don't worry about it. Perhaps this is another reason to work on moving to Ruby...
    • CommentAuthordhayes
    • CommentTimeDec 12th 2006 edited
     permalink

    $obj = new Test();
    $obj->member = 2;

    $obj->member += 2;

    echo $obj->member; // =4


    as for the first example, i'm not sure why you would need to create an object for basic arithmetic.. it's certainly possible, you'd just need to make the member names different.. or do something like:


    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


    .. should work :)
Add your comments
    Username Password
  • Format comments as (Help)