Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Closure in JavaScript vs PHP

I am trying to implement a very simple closure related task in PHP which is not going well. I have this solution in JavaScript. How do i implement this in PHP?

const data = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]

const getChunksOfTwo = () => {
  let pos = 0
  
  return () => {
     const start = pos
     const finish = start + 2
     const chunk = data.slice(start, finish)
     pos++
     return chunk
  }
}

// To initiate the closure
const closureFun = getChunksOfTwo()

// Call the closureFun
closureFun() // Gives [1, 2]
closureFun() // Gives [2, 3]
closureFun() // Gives [3, 4]

But in PHP the same apparently does not work. I am trying this:

$data = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];

function getChunksOfTwo($data) {
   $pos = 0;

   return function() {
     $start = $pos;
     $finish = $start + 2;
     $chunk = array_slice($data, $start, $finish);
     $pos++;
     return $chunk;
   };
};

// To initiate the closure
$closureFun = getChunksOfTwo($data);

// Call the closureFun
$closureFun(); // Does not give [1, 2]
$closureFun(); // Does not give [2, 3]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can try this

$data = [1,2, 3, 4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];

function getChunksOfTwo($data) {
   $chunks = array_chunk($data, 2);
   $pos = 0;
   
   return function() use(&$pos, $data, $chunks) {
     return $chunks[$pos++];
   };
};

// To initiate the closure
$closureFun = getChunksOfTwo($data);

// Call the closureFun
print_r($closureFun()); // Does not give [1, 2]
print_r($closureFun()); // Does not give [2, 3]

& with var means passing by reference source

It has to be passed by reference to mutate that variable otherwise it copies the original and every new call will have the same value.

Outupt

Array
(
    [0] => 1
    [1] => 2
)
Array
(
    [0] => 3
    [1] => 4
)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading