PHP: self vs $this – what’s the difference?

P

This is a very unique topic that I found very interesting. Inside a class with PHP you can access a property or method by using either: self::myVariable or $this->myVariable. Let’s explore the unique difference, specifically with how it relates to polymorphism.

Polymorphic class with self:: and $this

Imagine two classes, one that extends the other as follows:

[code]
class Shape {

function foo() {

}

function bar() {

}

}

class Rectangle extends Shape {

function foo() {

}

}
[/code]

The class Shape contains two functions and the class Rectangle extends shape and has one function that is overriding one of Shape’s functions.

Here is where it gets interesting. I’m going to update the classes as follows: foo in rectangle will output a specific message. The function bar in Shape will call foo. foo will then output a different message:

[code]
class Shape {

function foo() {
echo ‘Shape’;
}

function bar() {
$this->foo();
}

}

class Rectangle extends Shape {

function foo() {
echo ‘Rectangle’;
}

}
[/code]

Now the interesting part. Let’s instantiate the objects and look at the output:

[code]
var $rectangle = new Rectangle();

$rectangle->foo(); // Outputs Rectangle
$rectangle->bar(); // Also outputs Rectangle

var $shape = new Shape();

$shape->foo(); // Outputs Shape
$shape->var(); // Also outputs Shape
[/code]

The part that fascinated me was $rectangle->bar(); outputted Rectangle because $this is telling PHP to execute the function for the exact type of the current object. If this behavior is undesired, you can then change the bar function to:

[code]
function bar() {
self::foo();
}
[/code]

Then when you call $rectangle->bar(); it will output “Shape” instead because it is telling PHP to call the member function in the Shape class because that is where the function bar is defined, thus overriding the polymorphism behavior.

About the author

By Jamie

My Books