本文介绍了合并两个 PHP 对象的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有两个 PHP5 对象,想将其中一个的内容合并到第二个中.它们之间没有子类的概念,因此以下主题中描述的解决方案不适用.

We have two PHP5 objects and would like to merge the content of one into the second. There are no notion of subclasses between them so the solutions described in the following topic cannot apply.

你如何复制一个PHP 对象转换成不同的对象类型

//We have this:
$objectA->a;
$objectA->b;
$objectB->c;
$objectB->d;

//We want the easiest way to get:
$objectC->a;
$objectC->b;
$objectC->c;
$objectC->d;

备注:

  • 这些是对象,而不是类.
  • 对象包含相当多的字段,因此 foreach 会很慢.
  • 到目前为止,我们考虑将对象 A 和 B 转换为数组,然后在重新转换为对象之前使用 array_merge() 合并它们,但如果这样,我们不能说我们很自豪.
  • These are objects, not classes.
  • The objects contain quite a lot of fields so a foreach would be quite slow.
  • So far we consider transforming objects A and B into arrays then merging them using array_merge() before re-transforming into an object but we can't say we are proud if this.

推荐答案

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

当对象有方法时,这实际上也有效.(使用 PHP 5.3 和 5.6 测试)

This actually also works when objects have methods. (tested with PHP 5.3 and 5.6)

这篇关于合并两个 PHP 对象的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 03:48