接口(interface)是抽象方法和静态常量定义的集合。
接口是一种特殊的抽象类,这种抽象类中只包含抽象方法和静态常量。
接口中没有其它类型的内容。
我们先写接口的定义,下面的例子是接口的一个简单写法。
view sourceprint?1 interface 接口名{
2 }
下面的例子定义了一个接口 user ,这个接口中有两个抽象方法,getname() 和 setname()。能看到接口的写法和类很相似。
view sourceprint?1
2 interface user {
3 function getname();
4 function setname($_name);
5 }
6 ?>
注意,在接口中只能有抽象方法。如果在接口中出现了非抽象方法,会报错如下:
interface function user::setname() cannot contain body in ……….
view sourceprint?1
2 interface user {
3 function getname();
4 function setname($_name){}
5 }
6 ?>
程序运行如下:
view sourceprint?1 fatal error: interface function user::setname() cannot contain body in e:phpprojects est.php on line 4
在接口中的抽象方法只能是public的,默认也是public权限。
并且不能设置成 private 或者 protected 类型。
否则会报错如下:
access type for interface method user::setname() must be omitted in —on line —
在接口中,访问类型必须忽略。
view sourceprint?1
2 interface user {
3 public function getname();
4 private function setname($_name);
5 }
6 ?>
程序运行如下:
view sourceprint?1 fatal error: access type for interface method user::setname() must be omitted in e:phpprojects est.php on line 4
protected访问权限也会有问题
view sourceprint?1
2 interface user {
3 public function getname();
4 protected function setname($_name);
5 }
6 ?>
程序运行如下:
view sourceprint?1 fatal error: access type for interface method user::setname() must be omitted in e:phpprojects est.php on line 4
即使abstract 和 final 修饰符不能修饰接口中的抽象方法。
view sourceprint?1
2 interface user {
3 final function getname();
4 abstract function setname($_name);
5 }
6 ?>