在PHP中模拟多重继承 [英] Emulate multiple inheritance in php

查看:61
本文介绍了在PHP中模拟多重继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型系统:

abstract class R00_Model_iUnique { }
abstract class R00_Model_iFamilyUnique extends R00_Model_iUnique { } // for models with hierarchy
abstract class R00_Model_iTaggedUnique extends R00_Model_iUnique { } // for models with tags

// and, for example
class R00_Model_User extends R00_Model_iUnique { }
class R00_Model_Comment extends R00_Model_iFamilyUnique { }
class R00_Model_Post extends R00_Model_iTaggedUnique { }

会有R00_Model_iCommentableUnique,并且R00_Model_Post要从中继承.但是不可能,它已经从R00_Model_iTaggedUnique继承了,我认为从R00_Model_iCommentableUnique继承R00_Model_iTaggedUnique是聪明的,反之亦然.我只想到了一个实现方法的想法,但是我有一些疑问.也许您可以告诉我一些聪明的方法或批评这种方法?

There is gonna be R00_Model_iCommentableUnique and R00_Model_Post wants to be inherited from it. But It isn't possible, it's already inherited from R00_Model_iTaggedUnique, and I don't think It's clever to inherit R00_Model_iTaggedUnique from R00_Model_iCommentableUnique or vice versa. I've thought up only one idea how to implement it, but I have some doubts. Maybe you can tell me about some smart methods or criticize that method?

我考虑过让R00_Model_i * Unique不是类,而是接口,并创建诸如R00_Model_Helper_iUnique之类的帮助器对象(也许这是一个普通的模式,并且有一个很酷的名字,我不认为'Helper'将是很酷吗?).然后,在R00_Model_iUnique中,创建__call(),它检查被调用对象的所有接口并在帮助器中查找被调用方法.

I thought up to make R00_Model_i*Unique not classes, but interfaces, and create helper objects, such as R00_Model_Helper_iUnique (maybe it is a common patern, and there is a cool name, I don't think 'Helper' will be cool there?). Then, in R00_Model_iUnique, create __call(), which checks all the Interfaces of a called object and looks up a called method in the helper.

还是有太多的反思和其他邪恶的慢东西,不是吗?

Or there is too many reflection and other evil slow stuff, isn't it?

推荐答案

使用界面和帮助程序(合成)可以使您朝正确的方向前进.

You are in the right direction with using an interface and helpers (composition).

这恰恰是《设计模式手册》(GoF)的原则之一是继承时的偏爱" 的原因之一.

This is precisely one of the reasons why on of the principles of the Design Patterns Book (GoF) is "Favor composition over inheritance".

组合将为您提供使用不同类的方法所需的灵活性 在您需要的课程中.

Composition will give you the flexibility you require to use methods of different classes In the class that you need it.

这篇关于在PHP中模拟多重继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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