Jack Gajanan
Jack Gajanan

Reputation: 1670

operator override like .net in php classes

I have one class with multiple numeric values and functionality (for some kind of count category etc.)

class mBasicClass
{
    public $typ01Value = 0;
    public $typ02Value = 0;
}

I also have some other classes which are actually group of these classes

class mClass
{
    public $vjA = new mBasicClass();
    public $ntB = new mBasicClass();
    public $ntC = new mBasicClass();
    public $ntD = new mBasicClass();
}

All I want to know - is there any way to write operator override like .net in php classes

so that I can use

$vjA + $ntB 

Which actually is

$vjA->$typ01Value + $ntB ->$typ01Value
$vjA->$typ02Value + $ntB ->$typ02Value

Upvotes: 2

Views: 86

Answers (1)

Laurence
Laurence

Reputation: 60048

The request for PHP object operator overloading has been an open ticket since 2001:

https://bugs.php.net/bug.php?id=9331

So unfortunately you cannot do what you are asking :(

Instead you'll have to create a function like addObjects($obj1, $obj2) and do the manual calculations yourself:

addObjects($obj1, $obj2)
{
    $new_obj = new mBasicClass();
    $new_obj->typ01Value = $obj1->typ01Value + $obj2->typ01Value;
    $new_obj->typ02Value = $obj1->typ02Value + $obj2->typ02Value;

    return $new_obj;
}

then use it:

$result = addOjbects($vjA, $ntB);

Upvotes: 4

Related Questions