Merge Two or More PHP objects

Merge Two or More PHP objects
Merge Two or More PHP objects

While working on Object Oriented Programming Language, we often come in contact with large objects. Sometimes these objects are so big that it comes with one object embedded within another and so on. We’ll look into how to merge two or more PHP Objects in depth and different ways of doing that.

Few days back, I was assigned a task to show particular section of sub-block depending upon some condition.

So legacy codebase was having one API call which fetch data from remote resource and then from the response I got list of key-value pairs in terms of an array. Each individual array is then filtered and collected in separate array depending upon some condition.

blocks

We will simplify that code because that contains many other code.

Merge Two OR More PHP Objects Code-

Here is the complete code-

<?php

namespace src\classes\planDTO;

class planDTO
{
    public $plans = [];

    public function __construct($plans)
    {
        $this->plans = $plans;
    }

    public function checkValue($planId)
    {
        foreach ($this->plans as $k => $plan) {
            if ($plan['eventId'] == $planId) {
                $this->plans = $this->plans[$k];
                return $this->plans;
            }
        }
    }
}


namespace src\fooclass;

use src\classes\planDTO\planDTO;

class event
{
    public $id = 0;
    public $name = '';
    public $addr = '';

    public function __construct($id, $name, $addr)
    {
        $this->id = $id;
        $this->name = $name;
        $this->addr = $addr;
    }
}


// class event data
$arrEvent = [0 => ["id" => 1, "name" => "a", "addr" => "LA"], 
             1 => ["id" => 2, "name" => "b", "addr" => "DC"], 
             2 => ["id" => 3, "name" => "c", "addr" => "LV"]];
// class plan data
$arrPlanDTO = [0 => ["eventId" => 1, "planId" => 1, "name" => "student only"], 
               1 => ["eventId" => 2, "planId" => 2, "name" => "employee only"], 
               2 => ["eventId" => 3, "planId" => 3, "name" => "individual only"]];

$arrObj = [];
$i = 0;
$objPlans = new planDTO($arrPlanDTO);
foreach ($arrEvent as $val)
{
    $arrObj[$i] = new Event($val['id'], $val['name'], $val['addr']);
    if ($val['id'] != "")
    {
        $arrObj[$i]->planDetails = $objPlans->checkValue($val['id']);
    }
    $i++;
}

Here, we have defined two classes planDTO (API call) & event (that gets planDTO response in terms of array of objects).

We have also defined two array $arrEvent & $arrPlanDTO. Here in the next line of code, we have looped through each $arrEvent array element because we have to merge individual planDTO object inside event class. So, first we have created event class object inside foreach() which will loop through $arrEvent variable. We have passed id, name and addr as a parameter to the object of the event class.

This will store individual $arrEvent array element inside event object as follows.

So, when we print event object as a whole then it will look like this-

Array
(
    [0] => src\classes\event Object
        (
            [id] => 1
            [name] => a
            [addr] => LA
        )

    [1] => src\classes\event Object
        (
            [id] => 2
            [name] => b
            [addr] => DC
        )

    [2] => src\classes\event Object
        (
            [id] => 3
            [name] => c
            [addr] => LV
        )

)

Now, once filtration is done (checked if $val[‘id’] != “”) then we have executed checkvalue() method from planDTO class and passed $arrEvent individual event id. Once passed event id is matched with already stored plan event id then it will return that object in the plan variable as follows-

[planDetails] => src\classes\planDTO\planDTO Object
(
        [plans] => Array
        (
               [eventId] => 3
               [planId] => 3
               [name] => individual only
        )

)

Once we execute main code which will generate final output as follows

Array
(
    [0] => src\fooclass\event Object
        (
            [id] => 1
            [name] => a
            [addr] => LA
            [planDetails] => src\classes\planDTO\planDTO Object
                (
                    [plans] => Array
                        (
                            [eventId] => 1
                            [planId] => 1
                            [name] => student only
                        )

                )

        )

    [1] => src\fooclass\event Object
        (
            [id] => 2
            [name] => b
            [addr] => DC
            [planDetails] => src\classes\planDTO\planDTO Object
                (
                    [plans] => Array
                        (
                            [eventId] => 2
                            [planId] => 2
                            [name] => employee only
                        )

                )

        )

    [2] => src\fooclass\event Object
        (
            [id] => 3
            [name] => c
            [addr] => LV
            [planDetails] => src\classes\planDTO\planDTO Object
                (
                    [plans] => Array
                        (
                            [eventId] => 3
                            [planId] => 3
                            [name] => individual only
                        )

                )

        )

)

Other ways to Merge Objects

Apart from this method of merging two or more objects in PHP, we can also use array_merge() method to merge two objects.

Let’s see the action in example-

<?php

$foo = ["fooId"=>"1"];
$bar = ["barId"=>"2"];

$obj_merged = (object) array_merge($foo, $bar);
print_r($obj_merged);

?>
// OUTPUT

stdClass Object ( [fooId] => 1 [barId] => 2 )

As we can see, we have created two arrays and then merge these arrays using PHPs inbuilt function array_merge(). While merging we type cast that result into an object. This way our final array will be converted into object as shown above.

Use this method only when there is no importance of class name.

Conclusion:

We just saw two ways to Merge Two or More PHP objects. One with embedding one object directly into another object and other is merging two or more arrays into single array and then type-casting them into an object.