I got a fundamental question about the $this keyword in PHP and how it is defined. Pracitcally, I know what it is and what it does. But I am interested in how it is provided / implemented?
For example, in C++ or Java, it is passed as a hidden parameter when calling non static member functions / methods. So from the compilers point of view, it is basically a parameter. Here is what the JVM specification says for example:
On instance method invocation, local variable 0 is always used to pass a reference to the object on which the instance method is being invoked (this in the Java programming language).
But how is it defined in PHP? AI chatbots keep telling me that it is associated with a "method context". Is that true? So when calling $this in PHP, it would not access a secretly passed parameter, but rather access the "associated context" of the method and get the object-handle from there? Is this "method context" acutally just an object that represents the method execution, where all the parameters are stored, together with other meta-data like the $this variable? Something like a more complex stack frame.
Or is it something totally different? If someone knows better, could you please elaborate a little bit on it?
1 Answer 1
As far as I can tell (in the current development version of Zend PHP, at least) it is stored on the call frame1:
struct _zend_execute_data {
const zend_op *opline; /* executed opline */
zend_execute_data *call; /* current call */
zval *return_value;
zend_function *func; /* executed function */
zval This; /* this + call_info + num_args */
zend_execute_data *prev_execute_data;
zend_array *symbol_table;
void **run_time_cache; /* cache op_array->run_time_cache */
zend_array *extra_named_params;
};
When a method call is made, a frame is created, and the relevant object is stored in the This
member of the struct.
Instances of $this
in your code are compiled to the specialized opcode ZEND_FETCH_THIS
, which calls zend_fetch_this_var
when executed. The details are hidden behind macros, but I believe that (extremely simplified) this just sets the "result" value for the opcode to execute_data->This
.
1 A call frame is an item in the call stack. It keeps track of which function you're in, which instruction is currently being executed, assignment of local variables, and so on. One is created for every function call and it remains in use at least until the function returns.
$this
is the value of the calling object." — and that's all I could find too.