LoginSignup
1
0

More than 1 year has passed since last update.

PHP トレイト

Last updated at Posted at 2022-04-06

概要

コードを再利用するための仕組み。

定義

trait Move {
  function fowerd() {
    // 処理
  }

  function backwerd() {
    // 処理
  }
}

使用

class Human extends Animal  {
  use Move;

  public function walk() {
    $this->fowerd();
  }
}

詳細

トレイトは単一継承の制約を減らすために作られたもの。
メソッド群を異なるクラス階層にある独立したクラスで再利用できるようにする。
多重継承mixinにありがちな問題の回避ができる。

クラスに似ているが、トレイトは単に機能をまとめるだけもの。
インスタンスを作成することはできない

トレイトを活用すれば、継承しなくてもクラスのメンバーに汎用メソッドを追加できるようになる。

参考

PHP: トレイト

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0