如何合并两个对象? [英] How do I merge two objects?

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

问题描述

可能重复:
合并两个PHP对象的最佳方法是什么? /a>

Possible Duplicate:
What is the best method to merge two PHP objects?

我有一个对象$ foo,它已经定义了一些方法和属性,还有一个对象$ bar,它只是一组属性.我想将$ bar的全部合并到$ foo中,以便$ bar的所有属性都变成$ foo的属性.

I have an object, $foo, which has some methods and properties already defined and another object, $bar, which is just a set of properties. I want to merge the entirety of $bar into $foo such that all the properties of $bar become properties of $foo.

所以如果我之前有$ bar-> foobar,那么以后我应该可以使用$ foo-> foobar.

So if beforehand I had, $bar->foobar, afterwards I should be able to use $foo->foobar.

目前,我正在执行以下操作:

At the moment, I am doing the following:

foreach($bar as $key => $value) {
    $foo->$key = $value;
    }

但是,如果我使用数组,我将执行以下操作之一:

However, if I were using arrays, I would just do one of the following:

$foo += $bar;

$foo = array_merge($foo, $bar);

是否有类似的方法可以对对象执行此操作,或者我是否已经按正确的方法进行操作了?

Is there a similar way of doing this with objects or am I doing it the right way already?

请注意,我不会将$ bar本身变成$ foo的属性,即不是$ foo-> bar-> foobar

Please note that I do not what $bar to itself become a property of $foo i.e. not $foo->bar->foobar

推荐答案

如果$ bar具有$ foo的所有属性,则它是Foo.因此,您的Bar类应该从Foo继承(继承). (反之亦然,如果我把你的名字弄糊涂了!)

If $bar has all of $foo's properties, then it is a Foo. Thus, your Bar class should extend (inherit from) Foo. (Or vice versa, if I got your names confused!)

如果由于某种原因不想使用继承,则可以将一个对象保留在另一个对象中,并通过诸如__get()和__set之类的魔术方法动态地将调用从外部对象重定向到另一个对象的属性(请参见此处)

If you don't want to use inheritance for some reason, you can keep one object inside the other, and redirect calls to the other's properties from the outer object dynamically via magic methods like __get() and __set (see here)

这篇关于如何合并两个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆