When learning the interpreted language PHP, novice web programmers come across such a concept as the pseudo variable $ this. Its purpose and rules of use in the code are very different from all other variables, so it is worth dwelling on this issue in detail.
Classes and objects
Object-oriented programming (OOP), which has been used in PHP since version 5, provides the programmer with the ability to create any number of instances of the same class, called objects; in this case, each created copy gets its own name. An object can take data called arguments, process it with functions, and return a result. Any function of a class can access its properties not directly, but only through the object-> property construction, so the question arises: how to write such a universal code that will allow any generated object to work with data, regardless of its name? Consider the example shown in Figure 1.
This code declares a class that has a variable (property) and two functions (methods), one of which is a constructor, i.e. automatically starts when a new object is created. The job of the constructor function is to assign the data to the property that is received by the argument when the object is created. The method, when called, returns the value of the property.
Next, consider lines 12 and 13. In them, two new instances of the class are created, one of which receives the number 5 as an argument, and the other - 7. These values are assigned by the constructor function to a variable (property) that is accessible only within the class. Each created object is assigned to variables and accordingly (more precisely, these variables receive only references to the specified objects, but this does not matter at the moment). Now you can get the property values with a simple method call (lines 15 and 16).
Assigning the $ this pseudo variable
Please note: we have two different objects with exactly the same methods.
And this is where the pseudovariable comes to the rescue. Its name can be translated from English as "this", i.e. indicates (is a link) to the object in which it is located. As a result, line 5 for can be read as "assign the value of an argument to an object property", line 8 - "return the value of an object property". For, the variable will automatically take on the appropriate value.