PHP接口(interface
)做用相似于继承中的父类,接口是用于给其余的类继承用的,可是接口中定义的方法都是没有方法体的且定义的方法必须是公有的。
举例:php
<?php interface iTemplate{ public function eat($food); public function learn($code); } class student implements iTemplate{ public function eat($food){ echo "student eat {$food}"; } public function learn($code){ echo "student learn {$code}"; } } $student = new student(); $student->eat('apple'); echo '<br />'; $student->learn('PHP'); ?>
输出:app
student eat apple student learn PHP
接口中除了方法也是能够定义属性的,但必须是常量。code
<?php interface iTemplate{ public function eat($food); public function learn($code); const A='我是常量'; } class student implements iTemplate{ public function eat($food){ echo "student eat {$food}"; } public function learn($code){ echo "student learn {$code}"; } public function changliang(){ echo ITemplate::A; } } $student = new student(); $student->eat('apple'); echo '<br />'; $student->learn('PHP'); echo '<br />'; $student->changliang(); ?>
输出:继承
student eat apple student learn PHP 我是常量
那么既然是定义给其余类使用,就存在继承的问题,接口是能够多继承的。
举例:接口
<?php interface iTemplate1{ public function eat($food); } interface iTemplate2{ public function learn($code); } class student implements iTemplate1,iTemplate2{ public function eat($food){ echo "student eat {$food}"; } public function learn($code){ echo "student learn {$code}"; } } $student = new student(); $student->eat('apple'); echo '<br />'; $student->learn('PHP'); ?>
输出:io
student eat apple student learn PHP
这样就在student
类中继承了iTemplate1
和iTemplate2
接口,话能够先让iTemplate2
接口继承iTemplate1
接口,再让student
类去继承iTemplate1
接口,实现的效果同上。
举例:function
<?php interface iTemplate1{ public function eat($food); } interface iTemplate2 extends iTemplate1{ public function learn($code); } class student implements iTemplate2{ public function eat($food){ echo "student eat {$food}"; } public function learn($code){ echo "student learn {$code}"; } } $student = new student(); $student->eat('apple'); echo '<br />'; $student->learn('PHP'); ?>
输出:class
student eat apple student learn PHP
总结一下:方法
不对的地方还望dalao们指正。im