Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

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

Deprecated: Unbinding $this of closure is deprecated
PHP Fatal error:  Uncaught Error: Object of class Closure could not be converted to string

Fatal error: Uncaught Error: Object of class Closure could not be converted to string

After

PHP Warning:  Cannot unbind $this of closure using $this

Warning: Cannot unbind $this of closure using $this

PHP version change

This behavior changed in 8.0.

Error Messages

Extension

© 2023-2026, Damien Seguy - Exakat