php 如何扩展多个实用程序类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9818524/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 07:42:10  来源:igfitidea点击:

How to extend multiple utility classes

phpoop

提问by w00

This question is kinda aimed towards PHP but it probably applies to other languages aswell. In PHP you can only extend one class. But what if you need more classes?

这个问题有点针对 PHP,但它可能也适用于其他语言。在 PHP 中你只能扩展一个类。但是,如果您需要更多课程怎么办?

Suppose i have the following classes:

假设我有以下课程:

class MyClass extends Observer, Logger, OtherUtilClass

MyClass can't extend more than one class. But it needs to be an observer. And it might need some other base class aswell to fully function. What would be the best approach for this?

MyClass 不能扩展多个类。但它需要是一个观察者。它可能还需要一些其他基类才能完全发挥作用。什么是最好的方法?

回答by Starx

No

Your idea leads to multiple inheritanceand it is not available in PHP for good.

你的想法导致multiple inheritance它在 PHP 中永远不可用。

I extremelyrecommended you read thisquestion to see why you shouldn't try this.

强烈建议您阅读问题以了解为什么不应该尝试此问题。



However, you still can chain the classes. If done in a proper way you can get the functionality of all classes.

但是,您仍然可以链接这些类。如果以正确的方式完成,您可以获得所有类的功能。

Class Observer {}
Class Logger extends Observer {}
Class OtherUtilClasses extends Logger {}

//Now
class MyClass extends OtherUtilClasses {}

回答by jpic

In PHP 5.4, one class can use several traits.

在 PHP 5.4 中,一个类可以使用多个特征