PHP: self vs $this - what's the difference? PHP: self vs $this - what's the difference?

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:


class Shape {
	function foo() {
	}
	function bar() {
	}
}
class Rectangle extends Shape {
	function foo() {
	}
}

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:


class Shape {
	function foo() {
		echo 'Shape';
	}
	function bar() {
		$this->foo();
	}
}
class Rectangle extends Shape {
	function foo() {
		echo 'Rectangle';
	}
}

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


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

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:


	function bar() {
		self::foo();
	}

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.

Published on Jan 30, 2020

Tags: PHP | this | self

Related Posts

Did you enjoy this article? If you did here are some more articles that I thought you will enjoy as they are very similar to the article that you just finished reading.

Tutorials

Learn how to code in HTML, CSS, JavaScript, Python, Ruby, PHP, Java, C#, SQL, and more.

No matter the programming language you're looking to learn, I've hopefully compiled an incredible set of tutorials for you to learn; whether you are beginner or an expert, there is something for everyone to learn. Each topic I go in-depth and provide many examples throughout. I can't wait for you to dig in and improve your skillset with any of the tutorials below.