首頁 >後端開發 >php教程 >如何找出PHP对象数组的差值?

如何找出PHP对象数组的差值?

WBOY
WBOY原創
2016-06-06 20:25:471509瀏覽

《深入PHP 面向对象、模式与实践》的159页有下面的代码。
这儿是演示组合模式,removeUnit那个方法里用到了array_udiff函数。作者的本意是这样可以从 $units 属性里去除$unit 对象。我试了发现不起作用,关键就在$units参数里存的是对象,对象做比较时不能排序,所以就失败了。大家有没有好的方法可以从数组里排除掉一个对象吗?

<br>class Army extends Unit{

<code>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;
}   </code>

}

$army = new Army;

<code>$archer = new Archer();
//$archer->addUnit(new Archer);
$army->addUnit($archer);
$army->addUnit($archer);
$army->addUnit(new Archer);
$army->addUnit(new LaserCannonUnit);
</code>
<code>$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);</code>

回复内容:

《深入PHP 面向对象、模式与实践》的159页有下面的代码。
这儿是演示组合模式,removeUnit那个方法里用到了array_udiff函数。作者的本意是这样可以从 $units 属性里去除$unit 对象。我试了发现不起作用,关键就在$units参数里存的是对象,对象做比较时不能排序,所以就失败了。大家有没有好的方法可以从数组里排除掉一个对象吗?

<br>class Army extends Unit{

<code>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;
}   </code>

}

$army = new Army;

<code>$archer = new Archer();
//$archer->addUnit(new Archer);
$army->addUnit($archer);
$army->addUnit($archer);
$army->addUnit(new Archer);
$army->addUnit(new LaserCannonUnit);
</code>
<code>$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);</code>

直接循环和unset解决了。

<code>foreach($this->units as $k => $u){ 
         if($u === $unit){
             unset($this->units[$k]);
         }
     }</code>
陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn