This article is intended to introduce some understanding of the PHP $this variable to fellow students. I hope these articles will be helpful to you.
An interesting little example from the manual.
http://www.php.net/manual/zh/language.variables.basics.php
The code is as follows | Copy code | ||||
$name = 'this'; $$name = 'text'; // sets $this to 'text'echo $$name;
|
In the member method of the class, you can use -> (object operator): $this->property (where property is the name of the property) to access non-static properties.
When a method is called inside a class definition, there is a pseudo variable $this available. $this is a reference to the calling object (usually the object the method belongs to, but possibly another object if called statically from a second object).
This variable will have two states of existence during execution. One is the globally passed state, which is stored in EG(This). The other is the current scope state, which is stored in EG(active_symbol_table) (currently The execution environment's active symbol table).
When we execute an op_array, such as an object method, the PHP kernel will generate a zendexecutedata for this op_array. When generating initialization, EG(This) will be added to EG(active_symbol_table).
So where is EG(This) in an object initialized?
代码如下 | 复制代码 |
class Foo { public $var = 10; function t() { echo $this->var; } function t2() { echo 33; } } $foo = new Foo(); $foo->t(); |
The code is as follows | Copy code |
class Foo { Public $var = 10; function t() { echo $this->var; } Function t2() { echo 33; } } $foo = new Foo(); $foo->t(); |
The intermediate code generated by its main program flow is as follows:
代码如下 | 复制代码 |
function name: (null) number of ops: 8 compiled vars: !0 = $foo line # * op fetch ext return operands --------------------------------------------------------------------------------- 2 0 > NOP 15 1 ZEND_FETCH_CLASS 4 :1 'Foo' 2 NEW :1 3 DO_FCALL_BY_NAME 0 4 ASSIGN !0, 16 5 ZEND_INIT_METHOD_CALL !0, 't' 6 DO_FCALL_BY_NAME 0 7 > RETURN 1this |
The original object value of the variable is born in opcode NEW. After assignment (ASSIGN), the variable itself is passed to the caller of the execution environment during method initialization, and the caller passes the variable when executing the call (DO_FCALL_BY_NAME). For EG(This), when the op_array of this method is executed, when the environment of the current scope (zend_execute_data) is initialized, EG(This) will be added to the active symbol table as a $this variable, and the use of the $this variable in subsequent methods It will directly take the variables of the symbol table.