The $this keyword

742 0

As an example, we wrote a Car class that groups all the code that handles cars.

We also created two objects out of the class in order to be able to use its code:

The $this keyword indicates that we use the class’s own methods and properties, and allows us to have access to them within the class’s scope.

The $this keyword allows us to approach the class properties and methods from within the class using the following syntax:

• Only the this keyword starts with the $ sign, while the names of the properties and methods do not start with it.
The $this keyword indicates that we use the class’s own methods and properties, and allows us to have access to them within the class’s scope.
Let’s illustrate what we have just said on the Car class. We will enable the hello() method to approach the class’s own properties by using the $this keyword.
We use:

in order to approach the class $comp property. We also use:

in order to approach the class $color property.
That’s what the code looks like:

Let us create two objects from the class:

and set the values for the class properties:

We can now call the hello method for the first car object:

Result

Beep I am a BMW, and I am blue.
And for the second car object:

Result

Beep I am a Mercedes Benz, and I am green.
This is the full code that we have written in this Tutorial:

Comments

comments

In this article

Join the Conversation