なぜホームページを作るのですか?作るだけでは終わらない千客万来亭

PHP $this と self の違い

<?php
class A {
    protected static function method1() {
        echo "111\n";
    }

    public static function method2() {
        self::method1();
    }
}

class B extends A {
    protected static function method1() {
        echo "222\n";
    }
}

class C {
    protected function method1() {
        echo "111\n";
    }

    public function method2() {
        $this->method1();
    }
}

class D extends C {
    protected function method1() {
        echo "222\n";
    }
}

B::method2();

$v = new D;
$v->method2();

これを、以下のようにして実行すると、こうなります。

$ php /tmp/a.php
111
222

static の意味をうんぬん言うよりも、self はコンパイル時にすでに呼び出される関数が決定されているのに対して、$this の場合は実行時に呼び出し先が決まるということが分かってれば自明の結果と言えるかと。