Home » Php » How to merge two class in PHP?

How to merge two class in PHP?

Posted by: admin July 12, 2020 Leave a comment

Questions:

So that the final class have all member variables/methods in both class

Is there an easy way to go?

How to&Answers:

You should encapsulate the both classes in a containing class, and provide a relevant interface (such as setters/getters for private variables

class YourFirstClass {
   public $variable;
   private $_variable2;
   public function setVariable2($a) {
       $this->_variable2 = $a;
   }
}

class YourSecondClass {
   public $variable;
   private $_variable2;
   public function setVariable2($a) {
       $this->_variable2 = $a;
   }
}

class ContaingClass {
   private $_first;
   private $_second;
   public function __construct(YourFirstClass $first, YourSecondClass $second) {
       $this->_first = $first;
       $this->_second = $second;
   }
   public function doSomething($aa) {
       $this->_first->setVariable2($aa);
   }
}

Research (google): “composition over inheritance”

Footnote: sorry for non-creative variable names..

Answer:

Are you asking to do this at runtime, or at programming time?
I will assume runtime, in which case what is wrong with using class inheritance?
Create a new class which inherits from the two you want to merge.

Answer:

# Merge only properties that are shared between the two classes into this object.
public function conservativeMerge($objectToMerge)
{
    # Makes sure the argument is an object.
    if(!is_object($objectToMerge))
        return FALSE;

    # Used $this to make sure that only known properties in this class are shared.
    # Note: You can only iterate over an object as of 5.3.0 or greater.
    foreach ($this as $property => $value)
    {
        # Makes sure that the mering object has this property.
        if (isset($objectToMerge->$property))
        {
            $objectToMerge->$property = $value;
        }
    }
}


# Merge all $objectToMerge's properties to this object.
public function liberalMerge($objectToMerge)
{
    # Makes sure the argument is an object.
    if(!is_object($objectToMerge))
        return FALSE;

    # Note: You can only iterate over an object as of 5.3.0 or greater.
    foreach ($objectToMerge as $property => $value)
    {
        $objectToMerge->$property = $value;
    }
}

You should consider the first method as if it where the object counterpart of array_combine(). Then consider the second method as if it where the object counterpart for array_merge().