以下是问题的简化版本。
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;
输出结果为:
30
30
我希望将总数自动更新为50而不迭代数组并重新计算总和。是否可以使用PHP指针? 期望的输出:
30
50
答案 0 :(得分:1)
如果原点发生变化,总和不能改变。此信息丢失。但是,您可以使用魔术__set
方法向普通设置添加其他逻辑。在那里你可以打电话给"计算器"改变总数。
如果您不需要保留以前的界面,则应使用实际的值设置器(setValue
)来实现此目的,因为__set
不是很好的做法。
例如:
class A
{
private $value = 0;
private $b;
public function setObserver(B $b)
{
$this->b = $b;
}
public function __get($name)
{
if ($name == 'value') {
return $this->value;
}
}
public function __set($name, $value)
{
if ($name == 'value') {
$prev = $this->value;
$this->value = $value;
if ($this->b instanceof B) {
$this->b->change($prev, $this->value);
}
}
}
}
class B
{
public $total = 0;
public function __construct($values)
{
foreach ($values as $v) {
if ($v instanceof A) {
$this->total += $v->value;
$v->setObserver($this);
}
}
}
public function change($prevValue, $newValue)
{
$this->total -= $prevValue;
$this->total += $newValue;
}
}
打印:
30
50