在PHP中接口使用关键字interface
声明,在类体内不能有属性定义,只能由方法声明,并且不能在方法中定义任何功能代码。接口中定义的所有方法都是公有( public )的。
要在一个类中使用接口,需要使用implements
关键字。
语法:
class 类名 implements 接口名1,接口名2{}
设计需求:本实例在表单中输入学生的学号和学生姓名,然后单击【提交】按钮即可在页面中打印学生信息。
设计过程
- 新建
index.php
文件。并建立表单如下。
<form action="deal.php" method="post">
<div class="id">请输入学生学号:<input type="text" name="id"></div>
<div class="name">请输入学生名称:<input type="text" name="name"></div>
<div class="btn"><input type="submit" name="sub"><input type="reset" name="reset"></div>
</form>
- 新建
interface.php
文件。定义学生ID接口,在接口中声明用于设置学生ID的setId()
方法和获得学生ID的getId()
方法,代码如下。
interface Property_Id{ //学生学号接口
public function setId($id); //设置学生Id方法声明
public function getId(); //获取学生Id方法声明
}
- 在
interface.php
文件中定义学生名称接口,并在接口中声明学生姓名的setName()
方法和获得学生姓名的getName()
方法。代码如下。
interface Property_Name{ //学生姓名接口
public function setName($name); //设置学生姓名方法声明
public function getName(); //获取学生姓名方法声明
}
- 在
interface.php
文件中定义学生类Student,使其同时实现Property_Id和Property_Name接口,并实现类中所声明方法的定义。代码如下。
class Student implements Property_Id,Property_Name{ //定义学生类,使其实现Property_Id和Property_Name两个接口
private $id;
private $name;
public function setId($id){
$this->id = $id;
}
public function getId(){
return $this->id;
}
public function setName($name){
$this->name = $name;
}
public function getName(){
return $this->name;
}
}
- 新建
deal.php
文件用于处理index.php
文件发送过来的数据。
require "interface.php"; //包含接口类的文件
$id = $_POST['id']; //获取用户输入的学生id
$name = $_POST['name']; //获取用户输入的学生姓名
$student = new Student(); //对学生类进行初始化
$student->setId($id); //设定学生id
$student->setName($name); //设定学生名称
echo "当前学生学号为:".$student->getId();
echo "<br/>";
echo "当前学生姓名为:".$student->getName();