Home >Backend Development >PHP Tutorial >How to merge two objects in PHP? (code example)

How to merge two objects in PHP? (code example)

青灯夜游
青灯夜游Original
2019-03-12 14:06:1411871browse

In PHP, if given two objects of the same class, how to merge the two objects into a single object? The following article will introduce to you the method of merging two objects in PHP. I hope it will be helpful to you. [Video tutorial recommendation: PHP tutorial]

How to merge two objects in PHP? (code example)

Method 1: First convert the object into a data array, and then use array_merge( ) function to merge, and finally convert the merged data into a stdClass object.

Note: When using array_merge() to merge objects, the array elements in argument1 will be overwritten by the array elements in argument2. If the array in argument2 has null values, this may invalidate the resulting elements in the final object.

Example:

<?php 
class demo { 
    // 空类
} 
  
$objectA = new demo(); 
$objectA->a = 1; 
$objectA->b = 2; 
$objectA->d = 3; 
  
$objectB = new demo(); 
$objectB->d = 4; 
$objectB->e = 5; 
$objectB->f = 6; 
  
$obj_merged = (object) array_merge( 
        (array) $objectA, (array) $objectB); 
          
var_dump($obj_merged); 
  
?>

Output:

How to merge two objects in PHP? (code example)

Method 2:Create a new object of the original class and use The foreach loop assigns all properties of both objects to this new object.

Description: This is a simple and clean way to merge two objects.

Example:

<?php 
class demo { 
    // 空类
} 
$objectA = new demo(); 
$objectA->A = 1; 
$objectA->B = 2; 
$objectA->C = 3; 
$objectA->D = 4; 
$objectA->E = 5; 
$objectB = new demo(); 
$objectB->D = 6; 
$objectB->E = 7; 
$objectB->F = 8; 
  
// 用于转换给定对象类的函数
function convertObjectClass($objectA, $objectB, $final_class) { 
  
    $new_object = new $final_class(); 
  
    // 初始化类属性
    foreach($objectA as $property => $value) { 
        $new_object->$property = $value; 
    } 
      
    foreach($objectB as $property => $value) { 
        $new_object->$property = $value; 
    } 
  
    return $new_object; 
} 
  
$obj_merged = convertObjectClass($objectA,$objectB, &#39;demo&#39;); 
          
var_dump($obj_merged); 
  
?>

Output:

How to merge two objects in PHP? (code example)

The above is the entire content of this article, I hope it will be helpful to everyone's learning . For more exciting content, you can pay attention to the relevant tutorial columns of the PHP Chinese website! ! !

The above is the detailed content of How to merge two objects in PHP? (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn