2

我有一个具有多个数值和功能的类(对于某种计数类别等)

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

我还有一些其他类实际上是这些类的组

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

我想知道的-有没有办法在php类中编写像.net这样的运算符覆盖

这样我就可以使用

$vjA + $ntB 

实际上是

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

1 回答 1

4

自 2001 年以来,对 PHP 对象运算符重载的请求一直是公开的票:

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

所以不幸的是你不能做你所要求的:(

相反,您必须创建一个类似的函数addObjects($obj1, $obj2)并自己进行手动计算:

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

    return $new_obj;
}

然后使用它:

$result = addOjbects($vjA, $ntB);
于 2012-12-22T12:52:11.963 回答