Abstract classes and interfaces
In PHP, abstract classes can be declared through the abstract keyword. Sometimes we need a class to have certain public methods. In this case, we can use interface technology
1, create an animal class
##Animal.class.php code is as follows:
<?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, create a dog class
Dog.class.php code is as follows:<?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();
The running results are as follows:
##3, create a cat classCat.class.php code is as follows:
<?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();The running results are as follows:
Create the interface.php file, the code is as follows:
<?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();
operation result: