LoginSignup
4
1

More than 3 years have passed since last update.

コードでわかる$this->入門

Last updated at Posted at 2020-09-18

なんとなく$this->を使ったり、$this->ってなんだって思った駆け出しの方への記事です
かなり大雑把に説明していますが、これくらいの方が最初はイメージがつかみやすいと思います
他の素晴らしい記事の橋渡しになれば幸いです。

$thisはオブジェクト自身を表す特別な変数で
->はオブジェクトのメソッドやプロパティにアクセスするために使うアロー演算子というものです。
実際にコードで見ていきましょう。

example.php
<?php
//クラス
class Example {
    //プロパティ初期化
    public $int1 = 100;
    public $int2 = 200;
    //メソッド    
    function show()
    {
        //ローカル変数
        $int1 = 'int2';
        echo $this->int1;
        echo $this->int2;
        echo $this->$int1;
    }
}
//インスタンス化
$test = new Example();
//オブジェクトのメソッドを呼び出す
$test->show();
echo '------------';
//プロパティを変更する
$test->int1 -= 1;
//取得
echo $test->int1;
$test->show();

この実行結果は以下のようになります

100
200
200
----------
99
99
200
200

$this->$int1$this->int2に変換されるのがミソ
プロパティもメソッドも->で呼び出すことができる
またメソッドチェーンという連結する書き方もできる
$this->test()->example()みたいな感じ

4
1
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
4
1