PHP
類是單繼承触趴,也就是不支持多繼承终畅,當(dāng)一個(gè)類需要多個(gè)類的功能時(shí),繼承就無能為力了幽七,為此 PHP 引入了類的接口技術(shù)景殷。
接口的使用使用implements關(guān)鍵字,而對(duì)抽象類使用的是extends繼承關(guān)鍵字澡屡。
在接口中只能定義常量和方法猿挚,不能實(shí)現(xiàn)方法,const定義常量驶鹉,functionUser();不能使用pubilc
$a ="a"與 pubilc static$a
="a"绩蜻;
//抽象類
abstract class Father {
function name() {
echo "name...
";
}
abstract function name2();
public $n="n1";
public static $n2="n2";
const n3="n3";
}
class Data extends Father {
function name2() {
echo "name2 of Data...
";
}
}
$v=new Data();
echo $v->var1."
";
echo Father::$n2."
";
echo Father::n3."
";
//實(shí)現(xiàn)接口
interface User{
function getDiscount();
function getUserType();
}
//VIP用戶 接口實(shí)現(xiàn)
class VipUser implements User{
private $discount = 0.5;
function getDiscount() {
return $this->discount;
}
function getUserType() {
return "VIP用戶";
}
}
class Goods{
//public $price="45";??????? 此處接口定義中不能包含成員變量
//public static $price="45"; 此處接口定義中不能包含靜態(tài)變量
//
const price = 45;
public $vc;
//定義 User 接口類型參數(shù),這時(shí)并不知道是什么用戶
function run(User $vc){
$this->vc = $vc;
$discount = $this->vc->getDiscount();
$usertype = $this->vc->getUserType();
echo $usertype."商品價(jià)格:".self::price*$discount;
}
}
$display = new Goods();
$display ->run(new VipUser);?//可以是更多其他用戶類型
?>