最新消息: 新版网站上线了!!!

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

转载请注明:谷谷点程序 » php 中的 abstract, interface, final关键字