Simple example:
class a {
function first() {
echo 'a:first ';
}
function second() {
echo 'a:second ';
self::first();
}
}
class b extends a {
function first() {
echo 'b:first ';
}
function third() {
echo 'b:third ';
self::second();
}
}
$objB = new b();
$objB->third();
This will print:
b:third a:second a:firstbecause self does not care about the object instance.
If you replace, in a::second, the line
self::first()with the line
$this->first()the output will change to what you might have expected in the first place:
b:third a:second b:first
(As observed for PHP 5.3.3)
You have been warned :)
Thanks for pointing this out! This site also helped my understanding on this topic:
ReplyDeletehttp://www.programmerinterview.com/index.php/php-questions/php-self-vs-this/