php接口(interface
)作用类似于继承中的父类,接口是用于给其他的类继承用的,但是接口中定义的方法都是没有方法体的且定义的方法必须是公有的。
举例:
<?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'); ?>
输出:
student eat apple student learn php
接口中除了方法也是可以定义属性的,但必须是常量。
<?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'); ?>
输出:
student eat apple student learn php
这样就在student
类中继承了itemplate1
和itemplate2
接口,话可以先让itemplate2
接口继承itemplate1
接口,再让student
类去继承itemplate1
接口,实现的效果同上。
举例:
<?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'); ?>
输出:
student eat apple student learn php
总结一下:
不对的地方还望dalao们指正。
如对本文有疑问, 点击进行留言回复!!
thinkphp5 + ajax 使用formdata提交数据(包括文件上传) 后台返回json完整实例
网友评论