《深入PHP 物件導向、模式與實踐》的159頁有下面的代碼。
這兒是示範組合模式,removeUnit那個方法裡用到了array_udiff函數。作者的本意是這樣可以從 $units 屬性裡去除$unit 對象。我試了發現不起作用,關鍵就在$units參數裡存的是對象,對象做比較時不能排序,所以就失敗了。大家有沒有好的方法可以從數組裡排除掉一個對象嗎?
class Army extends Unit{
private $units = array();function addUnit(Unit $unit){ if(in_array($unit, $this->units, true)){ return; } $this->units[] = $unit;} function removeUnit(Unit $unit){ $this->units = array_udiff($this->units, array($unit), function ($a, $b) { return ($a === $b) ? 0: 1;}); } function bombardStrength(){ $ret = 0; foreach($this->units as $unit){ $ret += $unit->bombardStrength(); } return $ret;}
}
$army = new Army;
$archer = new Archer();//$archer->addUnit(new Archer);$army->addUnit($archer);$army->addUnit($archer);$army->addUnit(new Archer);$army->addUnit(new LaserCannonUnit);
$army2 = new Army();$army2->addUnit(new Archer);$army2->addUnit($archer);$army2->addUnit($archer);$army2->removeUnit($archer);$army->addUnit($army2);$army->addUnit($army2);print_r($army);echo $army->bombardStrength()."\n";$army->removeUnit($army2);$army->removeUnit($army2);$army->removeUnit($army2);$army->removeUnit($archer);echo $army->bombardStrength();print_r($army);
回複內容:
《深入PHP 物件導向、模式與實踐》的159頁有下面的代碼。
這兒是示範組合模式,removeUnit那個方法裡用到了array_udiff函數。作者的本意是這樣可以從 $units 屬性裡去除$unit 對象。我試了發現不起作用,關鍵就在$units參數裡存的是對象,對象做比較時不能排序,所以就失敗了。大家有沒有好的方法可以從數組裡排除掉一個對象嗎?
class Army extends Unit{
private $units = array();function addUnit(Unit $unit){ if(in_array($unit, $this->units, true)){ return; } $this->units[] = $unit;} function removeUnit(Unit $unit){ $this->units = array_udiff($this->units, array($unit), function ($a, $b) { return ($a === $b) ? 0: 1;}); } function bombardStrength(){ $ret = 0; foreach($this->units as $unit){ $ret += $unit->bombardStrength(); } return $ret;}
}
$army = new Army;
$archer = new Archer();//$archer->addUnit(new Archer);$army->addUnit($archer);$army->addUnit($archer);$army->addUnit(new Archer);$army->addUnit(new LaserCannonUnit);
$army2 = new Army();$army2->addUnit(new Archer);$army2->addUnit($archer);$army2->addUnit($archer);$army2->removeUnit($archer);$army->addUnit($army2);$army->addUnit($army2);print_r($army);echo $army->bombardStrength()."\n";$army->removeUnit($army2);$army->removeUnit($army2);$army->removeUnit($army2);$army->removeUnit($archer);echo $army->bombardStrength();print_r($army);
直接迴圈和unset解決了。
foreach($this->units as $k => $u){ if($u === $unit){ unset($this->units[$k]); } }