php+interface+abstract,php 中的 abstract, interface, final关键字

php5中引入了面向对象的概念,所以有了abstract 和 interface。这两个东西,对结构的意义大于对实现的意义。在stackoverflow上面,有人提问两者的差别,答案简明易懂。

在网友的答案中,两个例子很形象地描述了两者的区别:

interface:An interface is a contract: the guy writing the interface say "hey, I accept things looking that way", and the guy using the interface says "OK, the class I write looks that way".

abstract:It's more about a guy saying "these classes should look like that, and they got that in common, so fill in the blanks !".

interface适合co-work,它是种结构而不是class,使用时候开销比较小。abstract则是同类事物共同点的抽象,是个不能实例化的class,使用时候开销大。可以看出来,abstract确实是种父类,而interface不是,所以子类只能extend单个abstract,却可以implements(实现)多个interface。

当然,abstract和interface间显而易见的差别也有被列出来,但是,本质区别还是上面所述,之下也将区别列出:

1.Abstract classes can have consts, members, method stubs and defined methods, whereas interfaces can only have consts and methods stubs.

2.Methods and members of an abstract class can be defined with any visibility, whereas all methods of an interface must be defined as public.

3.When inheriting an abstract class, the child class must define the abstract methods, whereas an interface can extend another interface and methods don't have to be defined.

4.A child class can only extend a single abstract (or any other) class, whereas an interface can extend or a class can implement multiple other interfaces.

5.A child class can define abstract methods with the same or less restrictive visibility, whereas a class implementing an interface must define the methods with the exact same visibility.

============================================================================================================================================================================

final 和前面两个关键字不同,它主要用来限制访问。和public, protected等关键字一样,它的作用在于限制method被重写(如果用在method上)。它也可以用来定义class,从而限制其被访问

======================================================================================

参考链接:

http://stackoverflow.com/questions/1913098/what-is-the-difference-between-an-interface-and-abstract-class

http://stackoverflow.com/questions/4248021/when-to-use-final-in-php

http://www.php.net/manual/en/language.oop5.final.php

http://php.net/manual/en/language.oop5.abstract.php

http://php.net/manual/en/language.oop5.interfaces.php

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值