Dynamically reference to $this should not work, but it does

PHP uses a concept we call the compiled variables (CV) optimization. This means that instead of using a hashtable which maps variable names to their values, we use a plain array and index into it. The compiler knows which variable name corresponds to which index. Performing array index lookups is significantly faster than doing hashtable lookups.

The $this variable will also be stored this way and its index is specially remembered as op_array->this_var. If no $this use is found this value is left uninitialized at -1. When pushing a new execution context onto the VM stack PHP will check op_array->this_var and, if it isn’t -1, initialize the $this variable entry.

When a variable variable is accessed, PHP will walk through the CV table and construct a proper symbol hashtable from it. Of course it will only add variables which actually are in the CV table, so if it doesn’t contain $this you’ll end up with an undefined variable lookup.

Now consider your three cases:

  1. $this and ${"this"} are the same as far as the PHP compiler is concerned (after all the variable name is known at compile time in both cases).
  2. As the PHP 5.x compiler does not yet perform constant expression folding, it will however not be able to detect that ${"th"."is"} is a $this access as well. So this_var stays uninitialized.
  3. In the last case you have a plain $this usage, as such this_var will be set and also accessible through a variable-variable lookup.

Note that the situation is different in PHP 7 – we’ll always set this_var on a variable variable lookup, so indirect $this lookups should always work.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)