[Osaka/Yokohama] Looking for infrastructure/server side engineers!

[Osaka/Yokohama] Looking for infrastructure/server side engineers!

[Deployed by over 500 companies] AWS construction, operation, maintenance, and monitoring services

[Deployed by over 500 companies] AWS construction, operation, maintenance, and monitoring services

[Successor to CentOS] AlmaLinux OS server construction/migration service

[Successor to CentOS] AlmaLinux OS server construction/migration service

[For WordPress only] Cloud server “Web Speed”

[For WordPress only] Cloud server “Web Speed”

[Cheap] Website security automatic diagnosis “Quick Scanner”

[Cheap] Website security automatic diagnosis “Quick Scanner”

[Low cost] Wasabi object storage construction and operation service

[Low cost] Wasabi object storage construction and operation service

[Reservation system development] EDISONE customization development service

[Reservation system development] EDISONE customization development service

[Registration of 100 URLs is 0 yen] Website monitoring service “Appmill”

[Registration of 100 URLs is 0 yen] Website monitoring service “Appmill”

[Compatible with over 200 countries] Global eSIM “beSIM”

[Compatible with over 200 countries] Global eSIM “beSIM”

[Compatible with Chinese corporations] Chinese cloud / server construction, operation and maintenance

[Compatible with Chinese corporations] Chinese cloud / server construction, operation and maintenance

[YouTube] Beyond official channel “Biyomaru Channel”

[YouTube] Beyond official channel “Biyomaru Channel”

単一継承言語の救世主?? PHPのtraitについて解説!

PHP

お疲れ様です!
システム開発部の山田です。

今回は、PHP5.4.0から導入された、コードを再利用するために使用されるtraitについて解説していきます。

traitとは

traitはPHP5.4.0から導入され、単一継承言語でコードを再利用するための仕組みひとつです。
メソッド群を一つにまとめ、クラスの中で使用宣言を行うことで、継承を行わなくてもクラスメソッドとして使用することができる機能です。

何故traitが生まれたのか

PHPのclassには継承という仕組みがあります。
継承とは、既存のclassの内容を引き継ぎながら新しくclassを作成する仕組みです。

継承を行うことで、同一コードを記載する必要が無くなりますが、この継承は一つのclassに一つの継承しかできない仕様となっており、いくつかのメソッド群を色々なclassで使用したい場合は継承の関係が複雑になる事が多く、少し扱いにくい物となっておりました。

その問題の対処法の一つとしてtraitは誕生しました。
メソッド群をtraitとしてまとめ、class内でtraitの使用を宣言をするだけで使えるようにすることで、単一継承の仕組みで起こる複雑さを軽減させる事ができます。

使用方法

traitの作成方法

trait トレイト名 {

 public function メソッド名1() {
  処理
 }

 public function メソッド名2() {
  処理
 }
}

class内での使用方法

class クラス名 {

use 作成したtrait名;

// 以降class処理

}

実際のコードにて確認

実際にコードを記載して動くかを確認してみます。
確認内容としては以下とします。

  • 自身のクラスメソッドがきちんと動作するか
  • 継承元のクラスメソッドがきちんと動作するか
  • stateをクラス内で使用宣言した際に、きちんと動作するか

そのために、神になった気分で強い勇者を作ってみたいと思います。
設定は、人間を作る際は、名前と身長のみを定義し、勇者は人間の特性に加え、剣を振ることができる物とします。
そこに、「足が速くなる」「体が強くなる」といった身体強化の特性も付与し強い勇者を作成したいと考えます。
コードを記載する流れは以下となります。

  • 身体強化のstateを作成
  • 人間classを継承した勇者classを作成
  • 作成したstateを勇者classに継承し、実際に動くかを確認
 
trait EnhancedBody {

  public function fastRunner() { 
    echo '足が速くなる'; 
  }
 
  public function strongBody() {
    echo '体が強くなる'; 
  } 
}
 
class Human {
  public $name;
  public $height;

  public function __construct($name) {
    $this->name = $name;
    $this->height = rand(140, 190);
  }

  public function status() {
    echo "名前:{$this->name}、身長:{$this->;height}"; 
  }
}

class Swordsman extends Human {
  use EnhancedBody;

  public function swingTheSword() {
    echo "剣を振る"; 
  } 
} 

以上のコードを動かした結果を以下に記載

// 勇者classの作成
$taro = new Swordsman('taro');

// 人間classに定義されているメソッドの実行
$taro->status(); // 名前:taro、身長:150

// 勇者classに定義されているメソッドの実行
$taro->swingTheSword(); // 剣を振る

// 身体強化stateに記載さえているメソッドの実行
$taro->fastRunner(); // 足が速くなる
$taro->strongBody(); // 体が強くなる

以上より強い勇者を作ることができたため、classメソッド、継承元のclassメソッド、使用宣言したstateのメソッドを使用できることが分かります。

まとめ

今回は、単一継承言語でコードを再利用するための仕組みのひとつであるtraitについて解説してきました。
使う場面自体は限られた機能ではありますが、trait内でメソッドを記載し、使いたいclassにuse宣言をするだけで使用できるためコードの複雑性が減り、読みやすいコードになるため、ぜひ使ってみてください!

最後に

私が所属するシステム開発のサービスサイト「SEKARAKU Lab(セカラク ラボ)」を開設しました。
ビヨンドは、サーバーの設計・構築から運用までをワンストップでお任せいただけますので、サーバーサイド開発でお困りの方はお気軽にお問い合わせください。
SEKARAKU Lab:https://sekarakulab.beyondjapan.com/

この記事がお役に立てば【 いいね 】のご協力をお願いいたします!
1
読み込み中...
1 票, 平均: 1.00 / 11
9,953
X facebook はてなブックマーク pocket
[2024.6.30 CentOS support ended] CentOS server migration solution

[2024.6.30 CentOS support ended] CentOS server migration solution

[2025.6.30 Amazon Linux 2 support ended] Amazon Linux server migration solution

[2025.6.30 Amazon Linux 2 support ended] Amazon Linux server migration solution

[Osaka/Yokohama] Actively recruiting infrastructure engineers and server side engineers!

[Osaka/Yokohama] Actively recruiting infrastructure engineers and server side engineers!

The person who wrote this article

About the author

Yuki Yamada

Joined Beyond Co., Ltd. in 2021
My hobbies are karaoke and board
games.My board games can no longer fit on one shelf, so I would like to buy a new shelf, but I am sad because I don't have a place to put a shelf at home.
He has experience in mold design and sales, and has gained a wide variety of experience and has settled into a job as a server-side engineer.
He is currently working on server-side development using PHP and Python.
He also wants to learn a front-end language in the future, and is interested in Next.js, a React-based front-end framework.