Removing $this from a closure is deprecated¶
When a closure is created in a non-static method, it imports automatically the current object. Nowadays, it is not possible to remove that object from the closure, as it would not run anymore.
PHP code¶
<?php
class x {
private $p = 1;
function foo() {
return function () { return $this->p; };
}
}
$x = new x;
$closure = $x->foo();
print $closure->bindTo(null);
?>
Before¶
PHP Deprecated: Unbinding $this of closure is deprecated in /codes/UnbindingThis.php on line 13
Deprecated: Unbinding $this of closure is deprecated in /codes/UnbindingThis.php on line 13
PHP Fatal error: Uncaught Error: Object of class Closure could not be converted to string in /codes/UnbindingThis.php:13
Stack trace:
#0 {main}
thrown in /codes/UnbindingThis.php on line 13
Fatal error: Uncaught Error: Object of class Closure could not be converted to string in /codes/UnbindingThis.php:13
Stack trace:
#0 {main}
thrown in /codes/UnbindingThis.php on line 13
After¶
PHP Warning: Cannot unbind $this of closure using $this in /codes/UnbindingThis.php on line 13
Warning: Cannot unbind $this of closure using $this in /codes/UnbindingThis.php on line 13
PHP version change¶
This behavior changed in 8.0