Automatically updating a PHP object value based on sum of other object values

Viewed 77

Here is a simplified version of the problem.

class A{
public $value = 0;
}
class B{
    public $values;
    public $total = 0;
    function __construct($values) {
        foreach($values as $value){
            $this->values[] = &$value;
            $this->total += $value->value;
        }
    }
}

$a = new A;
$a->value = 10;
$b = new A;
$b->value = 20;
$x = new B(array($a, $b));
echo $x->total . "\r\n";
$b->value = 40;
echo $x->total;

The output is:

30
30

I want the total to be automatically updated to 50 without iterating on the array and recalculating the sum. Is it possible using PHP pointers? Desired Output:

30
50
1 Answers
Related