PHP中trait使用方法

2021-08-18 08:59:51 字數 2558 閱讀 9018

1.php中使用trait關鍵字是為了解決乙個類既想整合基類的屬性和方法,又想擁有別的基類的方法,而trait一般情況下是和use搭配使用的。

<?php 

trait drive \n";

}} class person

} class student extends person

} $student = new student();

$student->study();

$student->eat();

$student->driving();

?>

輸出結果如下:

study

eatdriving trait

上面的例子中,student類通過繼承person,有了eat方法,通過組合drive,有了driving方法和屬性carname。

2.如果trait、基類和本類中都存在某個同名的屬性或者方法,最終會保留哪乙個呢?

<?php 

trait drive

public function driving()

} class person

public function driving()

} class student extends person

} $student = new student();

$student->hello();

$student->driving();

?>

輸出結果如下:

hello student

driving from drive

因此得出結論:當方法或屬性同名時,當前類中的方法會覆蓋 trait的 方法,而 trait 的方法又覆蓋了基類中的方法。

3.如果要組合多個trait,通過逗號分隔 trait名稱:

use trait1, trait2;
4.如果多個trait中包含同名方法或者屬性時,會怎樣呢?答案是當組合的多個trait包含同名屬性或者方法時,需要明確宣告解決衝突,否則會產生乙個致命錯誤。

<?php 

trait trait1

public function hi()

}trait trait2

public function hi()

}class class1

?>

輸出結果如下:

使用insteadof和as操作符來解決衝突,insteadof是使用某個方法替代另乙個,而as是給方法取乙個別名,具體用法請看**:

<?php 

trait trait1

public function hi()

}trait trait2

public function hi()

}class class1

}class class2

}$obj1 = new class1();

$obj1->hello();

$obj1->hi();

echo "

";$obj2 = new class2();

$obj2->hello();

$obj2->hi();

$obj2->hei();

$obj2->hehe();

?>

輸出結果如下:

trait2::hello

trait1::hi

trait2::hello

trait1::hi

trait2::hi

trait1::hello

5.

trait 也能組合trait,trait中支援抽象方法、靜態屬性及靜態方法,測試**如下:

<?php 

trait hello

}trait world

abstract public function getworld();

public function inc()

public static function dosomething()

}class helloworld

}$obj = new helloworld();

$obj->sayhello();

$obj->sayworld();

echo $obj->getworld() . "

";helloworld::dosomething();

$obj->inc();

$obj->inc();

?>

輸出結果如下:

hello

world

get world

doing something

12

PHP中trait使用方法詳細介紹

說通俗點,php中使用trait關鍵字是為了解決乙個類既想整合基類的屬性和方法,又想擁有別的基類的方法,而trait一般情況下是和use搭配使用的。carname n class person class student extends person student new student stud...

php中iconv函式使用方法

iconv convert string to requested character encoding php 4 4.0.5,php 5 mb convert encoding convert character encoding php 4 4.0.6,php 5 用法 string mb c...

php中 iconv 函式使用方法

下面windows版的iconv檔案 libiconv 1.9.1.bin.woe32.zip 將這檔案解壓,將bin 下面的charset.dll,iconv.dll,iconv.exe拷貝到c windows 或其它的系統path中 ipaddr提醒你,這步是必須的,php iconv.dll也...