2017-03-15 66 views
0

我想比较两个对象,看看它们是否相同。在做这件事时,我需要忽略其中一个属性。将两个对象与一个属性区分开来吗? php

这是我当前的代码:

$exists = array_filter($this->products, function($stored, $key) use ($item) { 
    return ($stored == $item); 
}, ARRAY_FILTER_USE_BOTH); 

这将比较对象是完全一样。我需要因为这是对象的数组暂时$stored

+0

'unset($ stored-> quantity)' – Ahmad

+1

'return($ key =='quantity')|| ($ stored == $ item);' – AbraCadaver

回答

0

删除的quantity的属性,如果从他们身上你unset性能,它不仅会在array_filter情况下取消设置的属性。由于数组包含object identifiers,它实际上会从$this->products中的对象中删除属性。如果你想临时删除一个属性进行比较,只需保存它的副本,然后进行比较,然后将其添加回对象,然后返回比较结果。

$exists = array_filter($this->products, function($stored, $key) use ($item) { 
    $quantity = $stored->quantity;  // keep it here 
    unset($stored->quantity);   // temporarily remove it 
    $result = $stored == $item;   // compare 
    $stored->quantity = $quantity;  // put it back 
    return $result;      // return 
}, ARRAY_FILTER_USE_BOTH); 

另一种可能性是克隆对象并从克隆中取消设置属性。取决于对象的复杂程度,这可能不如效率高。

$exists = array_filter($this->products, function($stored, $key) use ($item) { 
    $temp = clone($stored); 
    unset($temp->quantity); 
    return $temp == $item; 
}, ARRAY_FILTER_USE_BOTH);