In PHP 5, what is the difference between using self
and $this
?
When is each appropriate?
self
refers current class(in which it is called),
$this
refers current object.
You can use static instead of self.
See the example:
class ParentClass {
function test() {
self::which(); // output 'parent'
$this->which(); // output 'child'
}
function which() {
echo 'parent';
}
}
class ChildClass extends ParentClass {
function which() {
echo 'child';
}
}
$obj = new ChildClass();
$obj->test();
Output: parent child