0

In PHP, how can I merge all the property values of two objects? I am hoping for a built in function in PHP, else if anyone can show me an easy way of doing it.

See code under, where I have $objectA and $objectB which I want to become $obj_merged.

$objectA = (object) [];
$objectA->a = 1;
$objectA->b = 1;
$objectA->d = 1;
  
$objectB = (object) [];
$objectB->a = 2;
$objectB->b = 2;
$objectB->d = 2;
  
$obj_merged = [
    'a' => 3,
    'b' => 3,
    'd' => 3
];
Markus Zeller
  • 5,528
  • 2
  • 29
  • 32
Niklas
  • 319
  • 6
  • 19
  • Does this answer your question? [What is the best method to merge two PHP objects?](https://stackoverflow.com/questions/455700/what-is-the-best-method-to-merge-two-php-objects) – Tangentially Perpendicular Apr 04 '21 at 10:26
  • 3
    This is not really a "merge", more like a sum. What have you tried? Are the properties set in stone, or can they change? You can just loop over the object properties like you would an array's keys, if needed. This is pretty basic. – Jeto Apr 04 '21 at 10:26

1 Answers1

2

What you want to achieve is a sum of the properties. A merge would overwrite the values. There is no built-in PHP function to do this with objects.

But you can use a simple helper function where you could put in as many objects as you like to sum up the public properties.

function sumObjects(...$objects): object
{
    $result = [];
    foreach($objects as $object) {
        foreach (get_object_vars($object) as $key => $value) {
            isset($result[$key]) ? $result[$key] += $value : $result[$key] = $value;
        }
    }
    return (object)$result;
}

$sumObject = sumObjects($objectA, $objectB);
stdClass Object
(
    [a] => 3
    [b] => 3
    [d] => 3
)
Markus Zeller
  • 5,528
  • 2
  • 29
  • 32