您的位置:首页 > 编程语言 > PHP开发

跟着百度学PHP[4]OOP面对对象编程-12-对象接口技术(interface)

2016-12-10 20:41 519 查看
PHP与大多数面向对象编程语言一样,不支持多重继承。也就是说每个类只能继承一个父类

[b]接口正是解决每个类只能继承一个父类这个问题的[/b]

接口用什么权限,继承的那个方法也要使用什么权限。

接口的声明使用:interface

接口的继承使用:implements

目录++++++++++++++++++++++++++++++++++++++++++++

00x1 接口的声明以及接口的引用(案例一)

00x2 如何继承多个接口(案例二)

00x3 判断某个对象是否实现了某个接口(案例三)

++++++++++++++++++++++++++++++++++++++++++++++

00x1 案例一

<?php
interface icaneat{           #使用interface声明一个接口
public function eat($food); //接口里面不需要有方法的实现
}
class Human implements icaneat{      #使用implements继承接口(不能使用extends),稍后要与接口对接的属性或者方法要与其一致。
public function eat($food){                            #如该行所示,要与接口的属性或者方法一致。
echo "i eating ".$food."\n";       //实现了某一个接口之后,必须提供接口中定义的方法的具体实现。
}23
}
$test=new Human();
$test->eat('apple');
?>
输出效果如下:
i eating apple


00x2 案例二

在implments使用后用逗号隔开即可实现对多个接口的继承。

格式:

  implements 接口1,接口2,....

<?php
interface icaneat{
public function eat($food);
}
interface hello{
public fuction hello($nihao);
}
class Human implements icaneat,hello{       #使用逗号隔开即可实现对多个接口的继承
public function eat($food){
echo "i eating ".$food."\n";
}
}
$test=new Human();
$test->eat('apple');

?>


00x3 案例三

使用instanceof关键词检验

范例:var_dump($object instanceof hello); #对象$object是否实现了hello接口

<?php
interface test
{
public function one($a);
}
interface test2
{
public function two($b);
}
class chengdaniu implements test,test2
{
public function one($a){
echo "我爱WEB安全技术!";
}
public function two($b){
echo "我要成大牛!";
}
}
$shi=new chengdaniu();
var_dump($shi instanceof test);
?>
输出效果如下所示:

boolean true

THE END
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐