方法一
自 PHP 5.4.0 起,PHP 實(shí)現(xiàn)了一種代碼復(fù)用的方法,稱為 trait。
Trait 是為類似 PHP 的單繼承語(yǔ)言而準(zhǔn)備的一種代碼復(fù)用機(jī)制。Trait 為了減少單繼承語(yǔ)言的限制,使開(kāi)發(fā)人員能夠自由地在不同層次結(jié)構(gòu)內(nèi)獨(dú)立的類中復(fù)用 method。Trait 和 Class 組合的語(yǔ)義定義了一種減少?gòu)?fù)雜性的方式,避免傳統(tǒng)多繼承和 Mixin 類相關(guān)典型問(wèn)題。
Trait 和 Class 相似,但僅僅旨在用細(xì)粒度和一致的方式來(lái)組合功能。 無(wú)法通過(guò) trait 自身來(lái)實(shí)例化。它為傳統(tǒng)繼承增加了水平特性的組合;也就是說(shuō),應(yīng)用的幾個(gè) Class 之間不需要繼承。
從基類繼承的成員會(huì)被 trait 插入的成員所覆蓋。優(yōu)先順序是來(lái)自當(dāng)前類的成員覆蓋了 trait 的方法,而 trait 則覆蓋了被繼承的方法。
trait traitTestOne{
public function test(){
echo "This is trait one <br/>";
}
public function testOne(){
echo "one <br/>";
}
}
trait traitTestTwo{
// public function test(){
// echo "This is trait two";
// }
public function testTwo(){
echo "two <br/>";
}
}
class basicTest{
public function test(){
echo "hello world\n";
}
}
class myCode extends basicTest{
use traitTestOne,traitTestTwo;
}
$test = new mycode();
$test->test();
$test->testOne();
$test->testTwo();
輸出:
This is trait one
one
two
方法二
class Parent1 {
function method1() {}
function method2() {}
}
class Parent2 {
function method3() {}
function method4() {}
}
class Child {
protected $_parents = array();
public function Child(array $parents=array()) {
$this->_parents = $parents;
}
public function __call($method, $args) {
// 從“父類"中查找方法
foreach ($this->_parents as $p) {
if (is_callable(array($p, $method))) {
return call_user_func_array(array($p, $method), $args);
}
}
// 恢復(fù)默認(rèn)的行為,會(huì)引發(fā)一個(gè)方法不存在的致命錯(cuò)誤
return call_user_func_array(array($this, $method), $args);
}
}
$obj = new Child(array(new Parent1(), new Parent2()));
print_r( array($obj) );die;
$obj->method1();
$obj->method3();
方法三
interface testA{
function echostr();
}
interface testB extends testA{
function dancing($name);
}
class testC implements testB{
function echostr(){
echo "接口繼承,要實(shí)現(xiàn)所有相關(guān)抽象方法!";
echo "<br>";
}
function dancing($name){
echo $name."正在跳舞!";
}
}
$demo=new testC();
$demo->echostr();
$demo->dancing("模特");