Why do we need static when declaring anonymous functions?

Just the other day, a question came from one of the subscribers regarding one of the posts of my telegram channel . He was confused by this piece of code.





<?php

usort($firstArray, static function($first, $second) {
    return $first <=> $second;
});
      
      



The question sounded like this:





Why make usort callbacks static?





And I thought this is a really good question to pay attention to.





What is the problem?

Let's start with the definition from the documentation to sync:





Anonymous functions, also known as closures , allow you to create functions that do not have a specific name. They are most useful as callable parameter values  , but they can have many other uses as well.





Anonymous functions are implemented using the Closure class  .





There, but almost no one reads this:





When declared in the context of a class, the current class will be automatically associated with it, making $ this available within the class's functions. If you don't want to automatically link to the current class, use static anonymous functions .





, losure , . , $this



:





,
<?php

class ExampleTest extends TestCase
{
 
    public function testBasicTest(): void
    {
        $array = [2, 1];
        usort($array, function ($first, $second) {
            var_dump($this);
            return $first <=> $second;
        });

     	  self::assertTrue(true);
    }

}
      
      



" ", .





, $this, , , , .





static:





<?php 

class LargeObject {
    protected $array;

    public function __construct() {
        $this->array = array_fill(0, 2000, 15);
    }

    public function getItemProcessor(): Closure {
        return function () { //    
            $a = 1;
            $b = 2;
            return $a + $b;
        };
    }
}

function getPeakMemory(): string
{
    return sprintf('%.2F MiB', memory_get_peak_usage() / 1024 / 1024);
}
$start = microtime(true);

$processors = [];
for ($i = 0; $i < 2000; $i++) {
    $lo = new LargeObject();
    $processors[] = $lo->getItemProcessor();
}

var_dump(getPeakMemory());

      
      



, string(10) "134.10 MiB"







, static 11 , string(8) "1.19 MiB"







, processors[]



, losures , , , .





, static . static, , .





P.S.

. - https://t.me/beerphp. .








All Articles