PHP 中的多重扩展
我听说不能使用两次扩展。
我有两个类:
Base32 和 SecureRandom
TOTP 需要的
。我怎样才能同时使用这两个呢?
I've heard that you can't use extend twice.
I have two classes:
Base32 and SecureRandom
Which I need for TOTP.
How can I use both of these for it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用接口或composition(包括其中一个类的实例作为该类的成员变量)。
接口允许您定义类中方法的原型。然后,类
实现
该接口,并且必须为接口中的每个原型定义一个方法。您只能直接从一个类继承(扩展
),但可以实现
任意数量的接口。如果您发现界面不太适合您的任务,只需使用组合即可。
Use interfaces or composition (include an instance of one of the classes as a member variable of the class).
Interfaces allow you to define prototypes for the methods in a class. A class then
implements
that interface and must define a method for each prototype in the interface. You can only inherit directly from one class (extends
) but you canimplements
an arbitrary number of interfaces.If you find that interfaces don't fit your task well, just use composition.
看看PHP5.4 Traits,它们解决了多重扩展的问题。
将它们与接口结合起来以获得 instanceof 功能。
例如:
结果将是:
Take a look into PHP5.4 Traits they kind of solving problem of multiple extends.
Combine them with interfaces to get instanceof functionality.
For example:
Result would be:
PHP 不允许多重继承。您需要扩展其中一个并将另一个作为私有变量或类似的变量。
PHP doesn't allow for multiple inheritance. You'll need to extend one of them and have the other as a private variable, or something like that.