接口或抽象类:使用哪一个? [英] Interface or an Abstract Class: which one to use?

查看:104
本文介绍了接口或抽象类:使用哪一个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请解释我什么时候应该使用PHP 界面,何时应该使用抽象类

Please explain when I should use a PHP interface and when I should use an abstract class?

如何将抽象类更改为界面

推荐答案

当您想强制在您的系统中工作的开发人员(包括您自己)实施一定数量的方法时,请使用接口他们将要构建的类。

Use an interface when you want to force developers working in your system (yourself included) to implement a set number of methods on the classes they'll be building.

当你想强迫在你的系统中工作的开发人员(包括你自己)实现一定数量的方法时,使用抽象类您希望提供一些有助于他们开发子类的基本方法。

Use an abstract class when you want to force developers working in your system (yourself included) to implement a set numbers of methods and you want to provide some base methods that will help them develop their child classes.

要记住的另一件事是客户端类只能扩展一个抽象类,而它们可以实现多个接口。因此,如果您在抽象类中定义行为合同,则意味着每个子类可能只符合单个合同。有时候这是一件好事,当你想强迫你的用户程序员沿着特定的路径行进时。其他时候会很糟糕。想象一下,如果PHP的Countable和Iterator接口是抽象类而不是接口。

Another thing to keep in mind is client classes can only extend one abstract class, whereas they can implement multiple interfaces. So, if you're defining your behavior contracts in abstract classes, that means each child class may only conform to a single contract. Sometimes this a good thing, when you want to force your user-programmers along a particular path. Other times it would be bad. Imagine if PHP's Countable and Iterator interfaces were abstract classes instead of interfaces.

当您不确定要走哪条路时,这种方法很常见(如下面的cletus )是创建一个接口,然后让你的抽象类实现该接口。

One approach that's common when you're uncertain which way to go (as mentioned by cletus below) is to create an interface, and then have your abstract class implement that interface.

这篇关于接口或抽象类:使用哪一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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