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 ';

class b extends a {
    function first() {
        echo 'b:first ';

    function third() {
        echo 'b:third ';

$objB = new b();

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
with the line
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 :)