方法一
自 PHP 5.4.0 起刊侯,PHP 實現(xiàn)了一種代碼復用的方法汁政,稱為 trait勉躺。
Trait 是為類似 PHP 的單繼承語言而準備的一種代碼復用機制侈百。Trait 為了減少單繼承語言的限制瓮下,使開發(fā)人員能夠自由地在不同層次結構內獨立的類中復用 method。Trait 和 Class 組合的語義定義了一種減少復雜性的方式钝域,避免傳統(tǒng)多繼承和 Mixin 類相關典型問題讽坏。
Trait 和 Class 相似,但僅僅旨在用細粒度和一致的方式來組合功能例证。 無法通過 trait 自身來實例化路呜。它為傳統(tǒng)繼承增加了水平特性的組合;也就是說织咧,應用的幾個 Class 之間不需要繼承胀葱。
從基類繼承的成員會被 trait 插入的成員所覆蓋。優(yōu)先順序是來自當前類的成員覆蓋了 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ā)一個方法不存在的致命錯誤
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 "接口繼承捅位,要實現(xiàn)所有相關抽象方法轧葛!";
echo "<br>";
}
function dancing($name){
echo $name."正在跳舞!";
}
}
$demo=new testC();
$demo->echostr();
$demo->dancing("模特");