1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

laravel クラス名::class って書き方って結局何なのさ?

Last updated at Posted at 2024-01-24

概要

今更ながら クラス名::classという記述がなんとなくでしか分かってなかったので簡単にまとめる。

内容

早速本題に移ろう。クラス名::classという記述は一体何なんだろうか。
お恥ずかしながら自分も「まあなんかいい感じにクラス名を解決してくれてるんだろうな」というように考え「こう書けばいいや」で深く考えていなかった。

結論から言うと「クラス名を含むフルネームスペースを文字列として取得」している。

例を上げて説明しよう。下記のような処理があったとする。(UserServiceがuseされているlaravelのコントローラーっぽいクラスだ。アクションが定義されていないのでコントローラーとは言えないかも。)

<?php

namespace App/Http/Controllers;

use App/Services/UserService;

class UserController
{

    $userServiceFullNamespace = UserService::class;

}

上記を実行した時$userServiceFullNamespaceには「App/Services/UserService」が格納されている。
これだけだとあまり恩恵が感じられないかもしれないので「面倒だから下記のような記載でいいじゃない」と思うかもしれない。

<?php

namespace App/Http/Controllers;

class UserController
{

    $userServiceFullNamespace = 'App/Services/UserService';

}

ど正論だ。間違いない。しかしながら基本的に使われるほかクラスはuseして使うことが定説となっており(場合によってはハードコーディングすることもあるが)、上記みたいなコードを書くとセオリーからズレている可能性はある。可読性などの問題も有る。

更に$userServiceFullNamespace = 'App/Services/UserService';の処理がUserControllerのメソッドごとに複数記載された状態でUserServiceのNamespaceが変更になったらどうするだろう?
エディタの一括置換などを使えば、複数のハードコーディングされたNamespaceを一瞬で書き換えられるが、そもそも一箇所でuseしていれば修正箇所は一箇所で済む。

勝手に名前解決してくれると開発者にとってはいいことづくしなのでクラス名::classが多様されているということのようだ。

※間違えていたらすみません。何なりとご指摘お待ちしています。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?