trait を使おう、第二弾です。
前回の → https://hacknote.jp/archives/24521/
まずは trait を宣言。今回は 3つ。
<?php
trait test_a
{
public function test_function()
{
echo "aa" ;
}
}
trait test_b
{
public function test_function()
{
echo "bb" ;
}
}
trait test_c
{
public function test_function()
{
echo "cc" ;
}
}
前回と異なり、それぞれの trait で function 名が被ってます。
こんな時、何もせずに trait を use すると
Fatal error: Trait method test_function has not been applied, because there are collisions with other trait methods on test // 衝突してるよ!
こんな感じでエラーとなります。
そんな時は、何を使うか、指定してやります。
class test
{
/** 使う trait を宣言する */
use test_a, test_b, test_c
{
/** test_a の test_function を(test_b, test_c の同名の function に代わって)使うよ! */
test_a::test_function insteadof test_b, test_c ;
}
}
$class = new test() ;
$class->test_function() ;
insteadof 句が重要ですね。
test_b の function を使いたい場合は
class test
{
use test_a, test_b, test_c
{
test_b::test_function insteadof test_a, test_c ;
}
}
こんな感じで、使いたいやつは前にしときます。
複数の trait を使う場合は使いそうですね。


