PHP

When should we use self or this in PHP

April 6, 2022

When should we use self or this in PHP

In this article we’ll learn when to use self or this in PHP – with best practices so you’re never in doubt

self or this in PHP thumb

What’s up programmer, how are you? Let’s learn more about PHP and object orientation!

First, it is good to understand the purpose of each of the instructions.

self: this statement will reference a class;

$this: this refers to the object you are using

Let’s see in practice each case!

Using the self

The self we will use to access the static methods of some class

Thus being able to execute your logic in our software

Take a look:

<?php

class Test {
 static function usingSelf() {
  echo "This is how we use self"; 
 }

 public function helloWorld() {
  self::usingSelf(); 
 }

}

$t = new Test();

$t->helloWorld();

Here we are calling the static method by the other method that exists in the class, so we access it via ::self

Using $this

Now with $this we can access the properties and methods of the object

See it in action:

<?php

class Test {
 public $prop = "A property";

 public function helloWorld() {
  $this->testingMethod();
  echo $this->prop;
 }

 public function testingMethod() {
  echo "A method";
 }

}

$t = new Test();

$t->helloWorld();

In this way, we call a method and a property with $this

Remembering that this way we access the object itself, that is, the properties and methods can generate different values for each instantiated object

Conclusion

In this article we learned when we should use self or $this in PHP

The self is for accessing static methods of a class

We use $this to access the methods and properties of an instance of an object

Do you wanna learn more about PHP? Click here!

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x