除了一个属性,比较两个对象? PHP

I am trying to compare two objects, to see if they are the same. While doing this, I need to ignore one of the properties.

This is my current code:

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

This will compare the objects are the same completely. I need to temporarily remove a property of quantity from $stored

Since this is an array of objects, if you unset properties from them, it will not unset the properties only in the context of array_filter. Because the array contains object identifiers, it will actually remove the properties from the objects in $this->products. If you want to temporarily remove a property for comparison, just save a copy of it before unsetting, then do your comparison, then add it back to the object before return the result of the comparison.

$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);

Another possibility is to clone the object and unset the property from the clone. Depending on how complex the object is, this may not be as efficient.

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