
批改狀態(tài):合格
老師批語:
trait可以實(shí)現(xiàn)代碼復(fù)用和實(shí)現(xiàn)擴(kuò)展功能。另外需要注意trait命名沖突的解決方案,還有trait可以和interface結(jié)合使用。以下簡(jiǎn)單演示。
// trait功能1:實(shí)現(xiàn)代碼復(fù)用,并演示優(yōu)先級(jí)
trait show{
public static function getAge(){
return __METHOD__;
}
}
class One{
public static function getAge(){
return __METHOD__;
}
}
class Two extends One{
use show;
public static function getAge()
{
return __METHOD__;
}
}
// 優(yōu)先級(jí):子類>trait>父類
// 可以分別注釋子類,trait的方法查看輸出結(jié)果,就可以得到優(yōu)先級(jí)
echo (new Two())->getAge();
/**
*
* trait功能2:實(shí)現(xiàn)擴(kuò)展功能,并演示trait成員方法命名沖突
*
*/
trait tDemo1{
public function display()
{
return __METHOD__;
}
public function getProps()
{
printf('<pre>%s</pre>',print_r(get_class_vars(__CLASS__),true));
}
}
trait tDemo2{
public function display()
{
return __METHOD__;
}
public function getMethods()
{
printf('<pre>%s</pre>',print_r(get_class_methods(__CLASS__),true));
}
}
trait tDemo3{
// use tDemo1,tDemo2;
// 解決命名沖突
use tDemo1,tDemo2{
tDemo2::display as td2;
// 以下錯(cuò)誤
// tDemo1::display as td1;
tDemo1::display insteadof tDemo2;
}
}
class Work1{
use tDemo3;
public $name='西瓜';
public $price=2;
public function getInfo()
{
return $this->name.":".$this->price;
}
}
echo (new Work1())->getInfo();
(new Work1())->getProps();
(new Work1())->getMethods();
namespace demo4;
// trait和interface組合
interface iDemo{
public static function index();
}
trait tDemo{
// 把接口中的抽象方法交給Interface實(shí)現(xiàn)
public static function index()
{
return __METHOD__;
}
}
class Hello implements iDemo{
use tDemo;
}
//
$obj=new Hello;
echo $obj->index();
微信掃碼
關(guān)注PHP中文網(wǎng)服務(wù)號(hào)
QQ掃碼
加入技術(shù)交流群
Copyright 2014-2025 http://ipnx.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號(hào)