Emulate multiple inheritance in php

[亡魂溺海] 提交于 2019-12-13 02:30:12

问题


I have a system of Models:

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 { }

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?


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?


回答1:


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

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.



来源:https://stackoverflow.com/questions/1641940/emulate-multiple-inheritance-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!