Home > Backend Development > PHP Tutorial > How Can I Efficiently Merge PHP Objects Without Inheritance?

How Can I Efficiently Merge PHP Objects Without Inheritance?

Barbara Streisand
Release: 2024-12-19 21:36:10
Original
564 people have browsed it

How Can I Efficiently Merge PHP Objects Without Inheritance?

Efficient Merging of PHP Objects

When working with PHP5 objects that do not exhibit inheritance relationships, merging their contents can be a challenge. Traditional subclass-based solutions are inapplicable in this scenario.

Problem Statement

Consider the following objects:

$objectA->a;
$objectA->b;
$objectB->c;
$objectB->d;
Copy after login

The goal is to obtain a third object, $objectC, that contains all the properties of $objectA and $objectB.

$objectC->a;
$objectC->b;
$objectC->c;
$objectC->d;
Copy after login

Solution

The most efficient method for merging objects is to cast them to arrays using (array) and then merge them using array_merge(). The merged array can then be cast back to an object using (object):

$obj_merged = (object) array_merge((array) $obj1, (array) $obj2);
Copy after login

This technique works effectively even if the objects have methods, as tested in both PHP 5.3 and 5.6.

Remarks

  • It is assumed that the objects contain only fields and no methods.
  • The foreach method is avoided for performance reasons, as it is slower for objects with numerous fields.
  • Converting objects to arrays and back may seem cumbersome but it is the most efficient solution.

The above is the detailed content of How Can I Efficiently Merge PHP Objects Without Inheritance?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template