很像抽象类中的抽象方法
要实现这个接口必须要实现这个接口的方法
使用接口(interface),可以指定某个类必须实现哪些方法,但不需要定义这些方法的具体内容。
接口是通过 interface 关键字来定义的,就像定义一个标准的类一样,但其中定义所有的方法都是空的。
接口中定义的所有方法都必须是公有,这是接口的特性。
实现(implements)
要实现一个接口,使用
*implements*
操作符。类中必须实现接口中定义的所有方法,否则会报一个致命错误。类可以实现多个接口,用逗号来分隔多个接口的名称。
<?php /** * Created by PhpStorm. * User: songhao * Date: 2018/6/5 * Time: 下午2:18 */ interface DataInterface{ public function get_data(); } interface EntityInterface{ public function get_entity_type(); } // 继承多个接口,用逗号分隔。 class Entity implements DataInterface,EntityInterface{ public function get_data() { return "数据..."; } public function get_entity_type() { return '类型...'; } } $entity = new Entity; var_dump( $entity instanceof Entity, $entity instanceof EntityInterface, $entity instanceof DataInterface );
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
<
?
php
/
*
*
*
Created
by
PhpStorm
.
*
User
:
songhao
*
Date
:
2018
/
6
/
5
*
Time
:
下午
2
:
18
*
/
interface
DataInterface
{
public
function
get_data
(
)
;
}
interface
EntityInterface
{
public
function
get_entity_type
(
)
;
}
/
/
继承多个接口,用逗号分隔。
class
Entity
implements
DataInterface
,
EntityInterface
{
public
function
get_data
(
)
{
return
"数据..."
;
}
public
function
get_entity_type
(
)
{
return
'类型...'
;
}
}
$
entity
=
new
Entity
;
var_dump
(
$
entity
instanceof
Entity
,
$
entity
instanceof
EntityInterface
,
$
entity
instanceof
DataInterface
)
;
|
输出: