ITHACK
~ みんなのIT部門 ~
【PHP/演習問題】トレイト(trait)[1]

【PHP/演習問題】トレイト(trait)[1]

問題

次の実行結果になるプログラムを作成してください。
なお、下記条件を満たすものとします。

  • 次の表のクラス・トレイトを作成する
  • 人間クラス、コンピュータークラスのインスタンスからaddメソッドを実行する
種類 名称 英記 トレイト メソッド
トレイト 計算トレイト Calculation add( $x, $y )
→ 2値の足し算を出力する
具象クラス 人間クラス Person Calculation
具象クラス コンピュータークラス Computer Calculation
=== Person   ===
123 + 456 = 579
=== Computer ===
12345 + 67890 = 80235

解答例

<?php

trait Calculation {
    
    public function add( $x, $y ) {
        $result = $x + $y;
        echo $x.' + '.$y.' = '.$result."\n";
    }
    
}

class Person {
    
    use Calculation;
    
}

class Computer {
    
    use Calculation;
    
}

echo "=== Person   ===\n";
$person = new Person();
$person->add(123, 456);

echo "=== Computer ===\n";
$computer = new Computer();
$computer->add(12345, 67890);

?>