4
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 3 years have passed since last update.

PHP $thisとselfの違い

Posted at

目的

  • $thisとselfの違いが説明できなかったので簡単にまとめてみる

$thisとは

  • webで調べたら下記のように記載されていた。

    $thisは、自分自身のオブジェクトを指し、インスタンス化した際、クラス内のメンバ変数やメソッドにアクセスする際に使う。
    
  • また、独習PHPには下記のように記載されていた。

    $thisはインスタンスメソッド内でのみ利用できる特別なメソッドで、現在のインスタンスを指します。
    

self::とは

  • webで調べたら下記のように記載されていた。

    self::は、自クラスを示す。
    static変数はインスタンス化せずに使用します。この場合$thisは使用できません。
    

簡単なまとめ

  • $thisは現在のインスタンスを表している。そのため静的メソッドはそもそもインスタンス化されていないから$thisは使用する事ができない。
  • self::は静的メソッドや静的プロパティを呼び出すことができる。

$thisself::の使い分け

項目 内容
$this インスタンス化されているメソッドやプロパティを呼び出す時に使用する
self:: 静的メソッドや静的プロパティを呼び出す時に使用する
4
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
4
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?