In plain English, how is $this used in PHP?
It’s such a simple concept to me in JavaScript, but for some reason in PHP I can’t get my head around this variable and its function. What, at any given point, is it referring to exactly? I have only tertiary experience with OOP, and I suspect that’s why it’s hard for me to understand its usage, but I’m trying to get better, and a lot of the code I examine uses this variable.
In Very Simple English:
Once inside an object’s function, you have complete access to its variables, but to set them you need to be more specific than just using the variable name you want to work with. To properly specify you want to work with a local variable, you need to use the special
$thisvariable, which PHP always sets to point to the object you are currently working with.For example:
Whenever you are inside a function of an object, PHP automatically sets the
$thisvariable contains that object. You do not need to do anything to have access to it.In Normal English:
$thisis a pseudo-variable which is available when a method is called from within an object context. It is a reference to the calling object (usually the object to which the method belongs, but possibly another object, if the method is called statically from the context of a secondary object)An example:
Output: