Yield trong php

 Dùng Yield chủ yếu để save memory

1 - Cách dùng 


Yield trả về 1 object dạng Generator, chứa các phần từ đã được add vào trước đó

<?php

function testYield() {

    

    for($i = 1; $i<10;$i ++) {

        yield 'index'.$i => $i;

    }

}


$generators = testYield();


foreach($generators as $key => $value) {

    var_dump($key, $value);

}


Response:

string(6) "index1"

int(1)

string(6) "index2"

int(2)

string(6) "index3"

int(3)

string(6) "index4"

int(4)

string(6) "index5"

int(5)

string(6) "index6"

int(6)

string(6) "index7"

int(7)

string(6) "index8"

int(8)

string(6) "index9"

int(9)


2 - Code compare memory usage giữa Yield và return 1 mảng

https://medium.com/@mena.meseha/use-yield-for-memory-optimization-in-php-eafdac7e5b24


Comments

Popular posts from this blog

Các câu hỏi liên quan đến restful API

Active record (Eloquent) trong Laravel và Data Mapper (Doctrine) trong Symfony

CI/CD diagram, infra