在php中可以通过abstract关键字声明抽象类,有时候我们需要一个类必须具备某些公共的方法,此时就可使用接口技术
1,创建一个animal类
Animal.class.php代码如下:<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2018/3/3 0003
* Time: 下午 2:13
*/
abstract class Animal{
public $gender; //性别
public $size; //尺寸
public function __construct($gender,$size){
$this->gender=$gender;
$this->size=$size;
}
//限制非抽象类都需要调用此方法
abstract protected function getGender();
//final要求每个子类必须存在该方法并且不能重写
final public function getSize(){
return $this->size;
}
}
2,创建一个dog类
Dog.class.php代码如下:<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2018/3/3 0003
* Time: 下午 2:20
*/
header('content-type:text/html;charset=utf8');
require './Animal.class.php';
class Dog extends Animal {
/**
* @return mixed
*/
public function getGender()
{
return "'$this->gender'狗";
}
}
$dog=new Dog('公','大');
echo $dog->getSize();
echo $dog->getGender();
运行结果如下:
3,创建一个cat类
Cat.class.php代码如下:<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2018/3/3 0003
* Time: 下午 2:22
*/
header('content-type:text/html;charset=utf8');
require './Animal.class.php';
class Cat extends Animal {
public function getGender()
{
return "'$this->gender'猫";
}
}
$dog=new Cat('母','小');
echo $dog->getSize();
echo $dog->getGender();
运行结果如下:
4,接口类的调用
创建interpace.php文件,代码如下:<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2018/3/3 0003
* Time: 下午 2:34
*/
header('content-type:text/html;charset=utf8');
//定义usb接口
interface usb{
public function connect(); //连接
public function transfer(); //传输
public function disconnect(); //断开
}
class mp3 implements usb{
public function connect()
{
// TODO: Implement connect() method.
echo "连接...
";
}
public function transfer()
{
// TODO: Implement transfer() method.
echo "传输...
";
}
public function disconnect()
{
// TODO: Implement disconnect() method.
echo "断开...
";
}
}
$mp3=new mp3();
$mp3->connect();
$mp3->transfer();
$mp3->disconnect();
运行结果: