LoginSignup
1
1

PHPのselfと$thisの違い

Posted at

はじめに

Swiftと違うからごっちゃになったのでメモ

$this

$this は、インスタンス自体を指す特別な変数です。インスタンス化されたオブジェクトの中からプロパティやメソッドにアクセスするために使われます。

class MyClass {
    private $prop = "property value";
    
    public function showProp() {
        echo $this->prop;
    }
}

$obj = new MyClass();
$obj->showProp(); // property value を出力します。

self

self は、静的(static)なプロパティやメソッド、または定数にアクセスするために使われます。self キーワードを使うことで、インスタンス化しなくてもクラスの静的メンバにアクセスできます。

class MyClass {
    const CONSTANT = "constant value";
    private static $staticProp = "static property value";
    
    public static function showStaticProp() {
        echo self::$staticProp;
    }
    
    public function showConstant() {
        echo self::CONSTANT;
    }
}

$obj = new MyClass();
$obj->showConstant(); // constant value を出力します。
MyClass::showStaticProp(); // static property value を出力します。

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