首页 >后端开发 >php教程 >如何找出PHP对象数组的差值?

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

WBOY
WBOY原创
2016-06-06 20:25:471507浏览

《深入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