
Introduction
$this is one of the most important and most useful things in PHP OOP (Object Oriented Programming). Unfortunately, it is also one of the most neglected. Plenty of people have heard of the keyword without ever knowing how to use it.
In this article I will explain briefly what $this is and how it works. If you have no knowledge of OOP at all, I recommend looking into that first so this article makes more sense.
What is $this and how does it work?
The $this keyword gives us access to the methods and properties of our class. It means we can call a method, or read a property, from inside the current class itself.
As an example, let us start by creating a simple class called Dog. We will use this class for the next examples in this post.
class Dog {
public $name;
public $age;
}
So, to read a property of our class, we use $this as shown below:
$this->name
The example above simply shows how to use the keyword correctly. Notice how we drop the $ and write name after the arrow, even though the property is declared as $name. It is worth remembering, otherwise you may spend a while wondering why your code does not run properly.
The $this keyword and methods
Now let us use $this inside a method of our class:
class Dog {
public $name;
public $age;
public function intro(){
echo 'Voici ' .$this -> name . ' et il a ' .$this -> age . 'ans.';
}
}
For our function to run, we have to create an object of the class ourselves and set the values of the class properties, then call the public method:
<?php
// Instantiate
$blacky = new Dog();
// Add the name property
$blacky->name = 'Toffee';
// Add the age property
$blacky->age = '2 months';
And finally, we call our function.
echo $blacky->intro();
What we have just done is bring the class properties into our function. The output will look something like this:
C’est Toffee et il a 2 mois.
$this also lets us call a method from inside another method of the same class. Here is a quick example, for which we will use a new class, where one method uses $this to call the other.
class Man{
public $name;
public function say(){
echo 'Bonjour ' . $this->name;
}
public function hello(){
$this->say;
}
}
Now let us create our object, set the values and return the function.
// Instantiate the object
$john = new Man();
// Add the name
$john->name ='john';
// Call the hello() method
echo $john->hello();
The result should be
Bonjour John
That is how you use $this inside a method and call another method of the same class.
Conclusion
All in all, as you can see, it is pretty handy. It takes a little while to get used to putting it in your code, of course, but once you have got the hang of it you will be using it around the clock.


