Use variables outside of $ sheet-each () - Laravel Excel

0

I have a function that imports an Excel with the Laravel-Excel library, and within that function in the $ sheet-> every (function ($ row)) {} I am adding the records in an array that I have declared inside the function but outside the $ sheet-> g (), the thing is that then below the whole function I can not use that array to make a return, it is as if it were not declared.

Do you know if there is a specific method or functionality of Laravel Excel to do it?

public function excel($code){
        $i = 0;
        $transact = array();

        $file = File::find($code);
        $url = $file->FILE_url;

            Excel::selectSheetsByIndex(0)->load($url, function ($sheet) use($i, $transact){

                $hoja->each(function ($row) use($i, $transact){

                        $inCode = $row['inCode'];
                        $prCode = $row['prCode'];

                        $transact[$i] = (int)$inCode;
                        $transact[$i] = (int)$prCode;                        

                        $i++;

                });

                    return $transact;
            });
    }

This way the $ i does not autoincrement and I can not return from $ transact however much I put global ahead.

    
asked by RuralGalaxy 09.08.2016 в 11:32
source

1 answer

2

The problem is that the closure you are passing as a parameter has its own context, where the variables passed by use are passed by value and not by reference. That is why they are not modifiable.

The way to modify these variables is to pass them by reference, using the & modifier:

$hoja->each(function ($row) use(&$i, &$transact){
  $inCode = $row['inCode'];
  $prCode = $row['prCode'];

  $transact[$i] = (int)$inCode;
  $transact[$i] = (int)$prCode;                        

  $i++;
});

Edition:

I leave you an example code, so that you understand the closures a little better:

<?php

class Test {
  private $a;

  public function run() {
    $this->a = "antiguo A";
    $b = "antiguo B";
    $c = "antiguo C";

    $fn = function() use($b, &$c) {
      $this->a = "nuevo  A";
      $b = "nuevo  B";
      $c = "nuevo  C";

      echo "modificando en closure: \$a = '{$this->a}' \$b = '$b' \$c = '$c'".PHP_EOL;
    };

    echo "Valor antes del closure: \$a = '{$this->a}' \$b = '$b' \$c = '$c'".PHP_EOL;
    $fn();
    echo "Valor despues del closure: '{$this->a}' \$b = '$b' \$c = '$c'".PHP_EOL;
  }
}


$test = new Test();

$test->run();

Output:

Valor antes del closure: $a = 'antiguo A' $b = 'antiguo B' $c = 'antiguo C'
modificando en closure: $a = 'nuevo  A' $b = 'nuevo  B' $c = 'nuevo  C'
Valor despues del closure: 'nuevo  A' $b = 'antiguo B' $c = 'nuevo  C'

It is important to note that an automatic linkage of $this is made, so that this property can be accessed without needing to indicate it in use (read )

I recommend reading Closure and areas .

    
answered by 09.08.2016 / 11:57
source