5
As of PHP 5.4, the Closures
(Or funções anônimas
), when declared within the context of a class method (other than static methods), automatically inherit to "within" the $this
as a reference to the class containing it.
Example:
class StackOverflow
{
protected $array = ['stack', 'overflow', 'portugues'];
public function testClosure($string)
{
$callback = function()
{
print_r($this);
/*
StackOverflow Object
(
[array:protected] => Array
(
[0] => stack
[1] => overflow
[2] => portugues
)
)
*/
return 'stack';
};
return preg_replace_callback('/stick/', $callback, $string);
}
}
(new StackOverflow)->testClosure('stick overflow');
As seen in the example, when we do the print_r($this)
, return the current instance of the class StackOverflow
.
However, if we made a small change and added the keyword static
before the anonymous function declaration, the variable $this
does not "matter" the class instance StackOverflow
inside:
public function testClosure($string)
{
// Closure static não importa o $this para o Escopo
$callback = static function()
{
print_r($this); // Undefined variable: this
return 'stack';
};
return preg_replace_callback('/stick/', $callback, $string);
}
As seen in the example, I am using the function preg_replace_callback
to be able to make changes in a string through a regex. I mean, I don’t need to have the $this
properly within the class, but I only want to use the Closure
as a callback
.
My question is this::
Since I will not use anything from the context of the current instance of class, we could say that it is more performatic to use the
static Closure
?Or the question of
$this
be "imported" into the scope does not mean loss of performance (since$this
ofClosure
does not receive a copy, but only creates the reference of the same instance of the class currently invoked)?
Just to point out, I’ve never heard of
Closure
could be declared asstatic
(I discovered the short time and I discovered these differences givingprint_r
) !But again, as @bigown says, the PHP manual is failing its users– Wallace Maxters