class Cl {
public function makeClosureWithoutThisUsed() {
return function () {
echo 'x';
};
}
public function makeClosureWithThisUsed() {
return function () {
$this->x = 'dummy';
echo 'x';
};
}
}
$cl = new Cl();
$fxWithoutThis = $cl->makeClosureWithoutThisUsed();
$fxWithThis = $cl->makeClosureWithThisUsed();
\Closure::bind($fxWithoutThis, null); // no $this used, no warning
\Closure::bind($fxWithThis, null); // $this used, warning emitted
$doesUseThis = function (\Closure $fx): bool {
// how to check if $fx uses $this?
};
var_dump($doesUseThis($fxWithoutThis)); // should print false
var_dump($doesUseThis($fxWithThis)); // should print true
When Closure
is not declared as static (static function () {...}
) it can be made effectively static by rebounding it to null
using Closure::bind
.
However, if there is an use of $this
inside, it will emit a warning like:
Warning: Cannot unbind $this of closure using $this in /in/7fX2Y on line 19
Is there is a better way (using reflection etc.) to detect if $this
is used than catching the php warning?
Aucun commentaire:
Enregistrer un commentaire