<?php
interface IActivity{ //接口中只需提供方法簽名,不能有成員變量
public function eat(); //接口中所有方法都必須是public方法
public function shout();
}
class Animal{
protected $_weight;
public function __construct($weight){
$this->_weight = $weight;
}
}
//用 implements 關鍵字聲明實現接口的類
//一個類可以實現多個接口,各個接口之間用逗號隔開
//要實現一個接口必須實現接口中定義的所有方法
class Pig extends Animal implements IActivity{
# 構造函數
public function __construct($weight){
parent::__construct($weight);
}
#自身的方法
public function nap(){
echo "A pig of $this->_weight kg is napping /n";
}
#實現接口的方法
public function eat(){
echo "A pig is eating ! /n";
}
#實現接口的方法
public function shout(){
echo "A pig is shouting ! /n";
}
}
$pig = new Pig(50);
$pig->nap();
#在使用接口的時候,往往是將一個變量指向類的實例,然後使用該變量訪問接口中的方法
$activity = $pig;
$activity->eat();
$activity->shout();
?>