php traits 使用,php中traits的使用
php是單繼承語言,但是如果想在一個class中實現多繼承的話,可以使用traits代替.
關于使用.使用關鍵字trait: 從某個方面,可以理解為class,但是不能實例化
trait中可以定義public,protected,private方法/屬性,且父類中如果使用trait,子類也會繼承trait,甚至private方法/屬性也能繼承
trait?Hello{
public?function?sayH(){
echo?'hello?';
}
protected?function?sayW(){
echo?'world';
}
private?function?pri(){
echo?'this?is?a?private?function';
}
static?public?function?wowo(){
echo?'this?is?a?static?function';
}
public?function?tst(){
echo?'this?is?trait';
}
}
class?one{
use?Hello;
public?function?say(){
$this->pri();
}
public?function?tst(){
echo?'this?is?one';
}
}
class?two?extends?one{
public?function?tst(){
echo?'this?is?two';
}
}
//偷懶,報錯的方法也假設可以執行下去
Hello::wowo();????????//this?is?a?static?function
$human?=?new?one();
$human->sayH();????????//hello
$human->sayW();????????//此處報錯,調用保護方法
$human->pri();????????//此處報錯,調用私有方法
$human->tst();????????//this?is?one
one::wowo();????????//this?is?a?static?function
$human->say();????????//可以內部調用?this?is?a?private?function
$people?=?new?two();
$people->sayH();????//hello
$people->sayW();????//報錯,調用保護方法
$people->pri();????//此處報錯,調用私有方法???!注意,私有屬性繼承下來了
two::wowo();????????//this?is?a?static?function
$people->say();????//內部調用?this?is?a?private?function
$people->tst();????//this?is?two
?>
可以發現,trait 中的 私有屬性 也可以繼續下來,可以理解為,two把use Hello 也繼承下來了,而且如果子類中有同名方法,則會覆蓋父類和trait中的方法
trait中還可以使用抽象類
trait?Hello{
abstract?public?function?say();
}
class?one{
use?Hello;
public?function?say(){
}
}
?>
當class one中不存在say方法時,便會報錯.
當有多個trait時,使用,隔開,或者使用復合traits
trait?Hello{
}
trait?World{
}
trait?HW{
use?Hello,World;
}
class?one{
use?Hello,World;
}
class?two{
use?HW;
}
?>
以上one 跟 two的實現效果是一樣的;
當兩個trait鐘的方法名一樣時,需要用關鍵字insteadof指定使用哪個,不然就會報錯,如果兩個都想保留,則可以用as通過別名來實現,同時as也可以實現對方法權限的更改
trait?H{
public?function?A(){
echo?'HA';
}
public?function?B(){
echo?'HB';
}
}
trait?W{
public?function?A(){
echo?'WA';
}
public?function?B(){
echo?'WB';
}
}
trait?Z{
public?function?A(){
echo?'ZA';
}
}
//若沒有use后{}里的說明,則會報錯
//Trait?method?A?has?not?been?applied,?because?there?are?collisions?with?other?trait?methods?on?HW
trait?HW{
use?H,W{
H::A?insteadof?W,Z;
W::B?insteadof?H;??//W中的B方法取代H中的B方法
Z::A?as?C;
A?as?protected;
}
}
class?one{
use?HW;
public?function?say(){
$this->A();
}
}
$a?=?new?one();
$a->say();????????//HA
$a->A();????????//因為被改變了權限,所以無法在外部調用
echo?'
';
$a->B();????????//WB
echo?'
';
$a->C();????????//ZA
?>
參考: http://blog.csdn.net/longlongmylove/article/details/7521379
總結
以上是生活随笔為你收集整理的php traits 使用,php中traits的使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: config database.php,
- 下一篇: AMD 最新显卡驱动存在 Bug,3DM