"If this automatic binding of the current class is not wanted, then static anonymous functions may be used instead. "
The main reason why you would not want automatic binding is that as long as the Closure object created for the anonymous function exists, it retains a reference to the object that spawned it, preventing the object from being destroyed, even if the object is no longer alive anywhere else in the program, and even if the function itself doesn't use $this.
<?php
class Foo
{
public function __construct(private string $id)
{
echo "Creating Foo " . $this->id, "\n";
}
public function gimme_function()
{
return function(){};
}
public function gimme_static_function()
{
return static function(){};
}
public function __destruct()
{
echo "Destroying Foo " . $this->id, "\n";
}
}
echo "An object is destroyed as soon as its last reference is removed.\n";
$t = new Foo('Alice');
$t = new Foo('Bob'); unset($t);
echo "---\n";
echo "A non-static anonymous function retains a reference to the object which created it.\n";
$u = new Foo('Carol');
$ufn = $u->gimme_function();
$u = new Foo('Daisy'); unset($u); echo "---\n"; echo "A static anonymous function does not retain a reference to the object which created it.\n";
$v = new Foo('Eve');
$vfn = $v->gimme_static_function();
$v = new Foo('Farid'); unset($v); echo "---\n";
?>
Because $ufn survived to the end of the end of the program, Carol survived as well. $vfn also survived to the end of the program, but the function it contained was declared static, so didn't retain a reference to Eve.
Anonymous functions that retain references to otherwise-dead objects are therefore a potential source of memory leaks. If the function has no use for the object that spawned it, declaring it static prevents it from causing the object to outlive its usefulness.