(I understand this may be a touchy decision, but I’d appreciate we avoid answers such as “Please don’t.”)
I have a class whose constructor takes a callback as an argument. In this callback, I think it would be most semantically correct that the $this variable be available as a reference to the instance to which the callback belongs. (I’ve noticed that 5.4 has reinstated $this in the context of anonymous functions defined within a class, however even that change wouldn’t help here as the function is passed as an argument to the constructor as mentioned)
The issue comes from the fact that the instance is not being passed as an argument to the callback, but instead made available by use()
use() has the tendency to cry about $this, stating it cannot be used as a lexical variable.
Is there a way, without passing it as an argument (any approach, use() or not, is likely fine) to accomplish this?
Off hand, the only thing I can think of would be something like:
... function($foo, $bar)
use($array_with_this){
extract($array_with_this); // contains instance with key 'this'
// code using $this
} ...
But this is forcing an additional requirement, which I’d rather not need.
This
$thisis a special keyword, you cannot use it outside of an object context. And anonymous functions currently run outside of the of the object context. This will change in the next version of PHP (5.4) apparently.