0
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?

[Laravel/PHPの基本]$thisって何?クラス内での役割と使い方を解説(実務でも頻出)

Posted at

はじめに

LaravelやPHPのクラス内でよく出てくる$this
この記事では、$thisの意味・使いどころ・Laravelでの実例を交えつつ、基本から解説します。

①$thisとは?

$thisは、今操作しているクラスのインスタンス自身を指します。
クラスの中から、自分自身(このクラスのプロパティやメソッド)にアクセスするときに使います。

②基本的な使い方

class User {
    public $name;

    public function setName($name) {
        $this->name = $name; //← 自分のプロパティにアクセス
    }

    public function greet() {
        return "こんにちは、" . $this->name . "さん";
    }
}

$user = new User();
$user->setName("田中");
echo $user->greet(); // ←こんにちは、田中さん

ポイント解説

  • $this->name → このクラスの中の$nameプロパティ
  • $this->setName() → このクラスの中のsetName()メソッド
  • インスタンス(newされたオブジェクト)ごとに$thisの中身は変わる

③Laravelでの$thisの例

コントローラーでの$this

class PostController extends Contoroller
{
    public function index()
    {
        return $this->getAllPosts();
    }
    private function getAllPosts()
    {
        return Post::all();
    }
}

→$this->getAllPosts()で、同じクラス内のメソッドにアクセスしています。

モデルやリクエストクラスでの$this

public function reles()
{
    return [
        'title' => 'required|string|max:255',
        'body' => 'required|string',
    ];
}

→Laravel内部では$this->rules()のように呼ばれて実行されていきます。

④よくある疑問:$thisとselfの違い

IMG_7812.jpeg

class Test {
    public static $type = 'テスト';

    public function show() {
        echo self::$type; // ← staticプロパティはselfでアクセス
    }
}

⑤実務での活用ポイント

  • クラス設計をするうえで、「自分自身にアクセスする」感覚が重要
  • Laravelはクラスベースなので、$thisを理解すればアプリ全体の構造もつかみやすくなる
  • Controller や Request, Model 内での $this->〇〇 はすべて同じクラス内の処理を呼び出していると考えるとわかりやすい

⑥まとめ

  • $thisは「今のクラスのインスタンス自身」を指す
  • 自分のプロパティやメソッドを$this->〇〇で操作する
  • Laravelでは、$thisはControllerやModelなど至るところで使われている
  • $thisを理解することで、Laravelのコードがぐっと読みやすくなる!
0
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
0
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?