As of PHP 5.4, Closures
, when declared within the context of a method of the class (other than static methods), automatically inherits the funções anônimas
as a reference of the class that contains 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 $this
, it will return the current instance of class print_r($this)
.
However, if we made a small change and added the keyword StackOverflow
before the declaration of the anonymous function, the variable static
does not "import" the instance of class $this
there in:
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'm using the StackOverflow
function to be able to make a string change through a regex . That is, I do not need to have preg_replace_callback
properly within the class, but I just want to use $this
as a Closure
.
My question is:
Since I will not use anything in the context of the current instance of the
class, could we say that it is more performative to use callback
?
Or the question of static Closure
being "imported" into the scope does not mean
loss of performasse (since $this
of $this
does not receive a copy, but will only create the reference of the same instance of the class currently invoked)?