Reassign $ this to PHP

(I understand this may be a touching decision, but I would appreciate it if we avoided answers such as "Please don't do this.")

I have a class whose constructor takes a callback as an argument. In this callback, I think it would be most semantically correct for the $this variable to be available as a reference to the instance to which the callback belongs. (I noticed that 5.4 restored $this in the context of anonymous functions defined in the class , however even this change will not help here, since the function is passed as an argument to the constructor as already mentioned)

The problem arises because the instance is not passed as an argument to the callback, but use() is available instead

use() tends to cry about $this , stating that it cannot be used as a lexical variable.

Is there a way, without passing it as an argument (any approach, use() or not, is most likely fine) to accomplish this?

On the right, the only thing I can think of is something like:

  ... function($foo, $bar) use($array_with_this){ extract($array_with_this); // contains instance with key 'this' // code using $this } ... 

But this forces an additional requirement, which I do not need.

+4
source share
1 answer
 $that = $this; cb(function () use ($that) { $that-> ... }); 

This $this is a special keyword; you cannot use it outside the context of an object. And anonymous functions are currently performed outside the context of the object. This is likely to change in the next version of PHP (5.4).

+6
source

All Articles