LoginSignup
1
4

More than 5 years have passed since last update.

$thisの役割

Posted at

プログラミング初心者であるため、内容に誤りがあるかもしれません。
もし、誤りがあれば修正するのでどんどん指摘してください。

$thisとの遭遇

はじめ$thisと遭遇した時は、意味がわからなく、必要性を感じませんでした。
下のコードの必要性はあるのかと疑問に思いました。

public function __construct($menuName, $userName, $body) {
    $this->menuName = $menuName;
    $this->userName = $userName;
    $this->body = $body;
  }

$thisの必要性

$thisとは、擬似変数と言われていますが、ピンときません。
$thisについて、調べてみると、クラス内のメンバ変数にアクセスするためには$thisを使用することがわかった。
コンストラクタや何かしらのfunctionを用いる時に、そのままでは、使えず、$thisを用いてひっぱてくる必要がある。
下のコードのように広くみるとわかる。

class Review {
  private $menuName;
  private $userName;
  private $body;

  public function __construct($menuName, $userName, $body) {
    $this->menuName = $menuName;
    $this->userName = $userName;
    $this->body = $body;
  }
}

まとめ

PHPを勉強し始めて思ったことがあります。
「わからないことが増えてきたが、少し遠目から見てみると、解決することもあるのだな」と。

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