在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 "连接...<br>"; } public function transfer() { // TODO: Implement transfer() method. echo "传输...<br>"; } public function disconnect() { // TODO: Implement disconnect() method. echo "断开...<br>"; } } $mp3=new mp3(); $mp3->connect(); $mp3->transfer(); $mp3->disconnect();
運行結果:
#下一節