Follow @endyourif rss Facebook LinkedIn

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

Published on Jan 30, 2020

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.

Tags: PHP | this | self

My Books
ASP.NET MVC 5 With Bootstrap and Knockout.js
Knockout.js Building Dynamic Client-Side Applications
20 Recipes for Programming MVC 3
20 Recipes for Programming PhoneGap
Rapid Application Development with CakePHP