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

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

问题描述

请解释什么时候应该使用 PHP interface 以及什么时候应该使用 抽象类?

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天全站免登陆