Wednesday, March 9, 2011

PHP: self versus this

If you haven't thought about it yet, self in PHP refers to class methods visible for the particular class, whereas this refers to the object methods visible for the instantiated object.

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:first
because 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 :)

1 comment:

  1. Thanks for pointing this out! This site also helped my understanding on this topic:

    http://www.programmerinterview.com/index.php/php-questions/php-self-vs-this/

    ReplyDelete