A generator allows you to write code that uses foreach to iterate over a set of data without needing to build an array in memory, which may cause you to exceed a memory limit, or require a considerable amount of processing time to generate.
В общем статическая анонимная функция прибавляет немного производительности в отличие от обычной анонимной функции. Если нам не нужен $this в этой фнкции, то мы можем указать static, но это некритично.
It is worth noting that in context of a class, static anonymous functions yield micro performance improvements and may be suggested in any instances which you do not need the containing class to be bound to the anonymous function.
Сайт, на котором собран 61 PHP-инструмент для анализа кода, управления зависимостями, тестов: https://phpqa.io/
А в этом репозитории ещё свыше ста линтеров, форматтеров и статических анализаторов: https://tprg.ru/lptv
#php #инструментыt.me/tproger_web/1004
$gen = (function() {
yield 1;
yield 2;
// 3 is only returned after the generator has finished
return 3;
})();
foreach ($gen as $val) {
echo $val, PHP_EOL;
}
echo $gen->getReturn(), PHP_EOL;
// Outputs 1 2 3
<?php
function xrange($start, $limit, $step = 1) {
if ($start <= $limit) {
if ($step <= 0) {
throw new LogicException('Step must be positive');
}
for ($i = $start; $i <= $limit; $i += $step) {
yield $i;
}
} else {
if ($step >= 0) {
throw new LogicException('Step must be negative');
}
for ($i = $start; $i >= $limit; $i += $step) {
yield $i;
}
}
}
/*
* Note that both range() and xrange() result in the same
* output below.
*/
echo 'Single digit odd numbers from range(): ';
foreach (range(1, 9, 2) as $number) {
echo "$number ";
}
echo "\n";
echo 'Single digit odd numbers from xrange(): ';
foreach (xrange(1, 9, 2) as $number) {
echo "$number ";
}
?>
class PostsCollectionFilter
{
public function unpublished($posts)
{
return $posts->filter(static function ($post) {
return ! $post->published;
});
}
}
class Book{
public static $name = 'Kirill';
public static function author()
{
return "the author name is ". self::$name;
}
public static function getAuthor(){
echo static::author();
}
}
class NewBook{
public static function author()
{
return "the author name is ". self::$name . " and K";
}
}
Book::getAuthor(); //he author name is Kirill
NewBook::getAuthor(); //he author name is Kirill and K