In PHP 5, what is the difference between using self
and $this
?
When is each appropriate?
$this
to refers to the current object.static
refers to the current object.self
refers to the exact class it was defined in.parent
refers to the parent of the exact class it was defined in.See the following example which shows overloading.
newThisClass()); // B
var_dump($b->newParentClass()); // A
class C extends B
{
public static function newSelfClass()
{
return new self;
}
}
$c = new C;
var_dump($c::newStaticClass()); // C
var_dump($c::newSelfClass()); // C because self now points to "C" class
var_dump($c->newThisClass()); // C
var_dump($b->newParentClass()); // A because parent was defined *way back* in class "B"
Most of the time you want to refer to the current class which is why you use static
or $this
. However, there are times when you need self
because you want the original class regardless of what extends it. (Very, Very seldom)