>  기사  >  백엔드 개발  >  如何找出PHP对象数组的差值?

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

WBOY
WBOY원래의
2016-06-06 20:25:471481검색

《深入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으로 문의하세요.