抽象クラスとインターフェイス
#PHP では、abstract キーワードを使用して抽象クラスを宣言できます。場合によっては、クラスに特定のパブリック メソッドが必要になることがあります。この場合、インターフェイス テクノロジを使用できます
1、動物クラスを作成します
##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.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();
実行結果は次のとおりです:
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、インターフェイス クラスを呼び出します
interface.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();
操作結果: