I\'ve the following PHP method which is part of the codebase which was working fine:
If you want it to work the same way it did before, you should not remove $this as a parameter. You should change the name of the parameter to something else, and change the corresponding variable name in the closure.
Through PHP 5.6, using $this as a parameter in a closure in a class method would mask the $this referring to the parent object. For example:
class Example
{
public function test ($param) {
$closure = function ($whatever) { // $this not used as parameter
return $this; // $this refers to the Example object
};
return $closure($param);
}
public function test2 ($param) {
$closure = function($this) { // $this used as parameter
return $this; // $this no longer refers to Example object
};
return $closure($param);
}
}
$ex = new Example;
$not_masked = $ex->test('foo');
$masked = $ex->test2('foo');
var_dump($not_masked, $masked);
Working example on 3v4l.org
In PHP 5.6, $masked would be the string 'foo', not the $ex object.
According to the output for the different versions that you can see at the 3v4l.org link, there was a brief period from 7.0.0-7.0.6 where the $this parameter would apparently be disregarded in favor of the object self-reference. I assume they disallowed using $this as a parameter in later versions to avoid the ambiguity of what $this actually referred to in the closure scope.
It looks like this was just confusing naming in the original code. In order to make it work as before:
->andReturnUsing(function ($anyOtherName) {
return $anyOtherName;
});