PHP Manual explained this in Late Static Bindings although perhaps it is not as concise as it should be.
Allow me to offer my own explanation.
Here is the guideline:
self always refers to the class where the word self appears.
static always refers to the current class in static context, even if the class is extended.
$this always refers to the current class in object context, even if the class is extended.
As shown in the following example, use self if you want to always refer to class A,
use static and $this if you want to always refer to class B, when B is the current class.
class A {
public function test() {
echo self::who(); // always class A
echo static::who(); // always the current class (static context)
echo $this->who(); // always the current class (object context)
}
public function who() {
echo __CLASS__ . "\n";
}
}
class B extends A {
public function who() {
echo __CLASS__ . "\n";
}
}
(new B)->test();
Output:
A
B
B
As you can see, static and $this refer to the same class (class B).
Let's extend the example with another class that extends class B:
class C extends B {
public function who() {
echo __CLASS__ . "\n";
}
}
(new C)->test();
Output:
A
C
C
Notice that static and $this refer to the same class again, class C this time,
because static and $this always refer to the current class, even if the class is extended.
So what is the difference between static and $this?
The difference is the context.
$this requires an object (a class instance), while static does not.
Let's see what happens if test() is called in static context:
C::test();
Output:
A
C
Fatal error: Using $this when not in object context in C:\wamp\www\test.php on line 7
The first and the second calls work fine in static context but the third call fails because $this requires object context.
See the code in action at https://ideone.com/AVtITz