I have the following class in PHP5.3:
class MyClass {
public $a=1;
public $hook;
function setHook(){
$t=$this;
$this->hook=function() use($t){
echo $t->a;
};
}
}
The following syntax works as expected:
$x = new MyClass();
$x->setHook();
call_user_func($x->hook); // outputs 1;
However if I continue with this code:
$y = clone $x;
$y->a = 2;
call_user_func($y->hook);
Then it would still output 1. I understand WHY it’s happens, because i’ve assigned a local variable which got embedded into the definition of my closure and subsequently into the “hook” property.
Please suggest how to get around this problem. For a class containing property with “callable” how do I clone it and make closures properly reference current object. Perhaps I can follow a different pattern. Thanks!
You could simply overwrite the
$hookwhen you clone:Not sure if your example is representative of your actual code. I hope it helps.
In PHP 5.4, you can use
Closure::bindToand$thisdirectly in the closure: