3

Here's my anonymous function:

<td><?=call_user_func(function($x) { if ($x == 1) { echo $produto->retornaMedida($dadosProdutos[$t]->medida_id); } else if ($x == 2) { echo "N/A"; } }, $dadosProdutos[$t]->produto_id)?></td>

It works perfectly well if I don't use something "out of scope" inside the scope of the conditions, like this:

<td><?=call_user_func(function($x) { if ($x == 1) { echo "Whatever"; } else if ($x == 2) { echo "N/A"; } }, $dadosProdutos[$t]->produto_id)?></td>

But when I use $dadosProdutos, for example, I get a:

[24-Dec-2015 03:47:58 America/Sao_Paulo] PHP Notice:  Undefined variable: dadosProdutos in G:\Insanity\Web\xampp\htdocs\sisconbr-old\site\modulos\pedido\minhas-cotacoes.php on line 269

And $dadosProdutos is not "undefined" when used out of the anonymous function:

<td><?=$produto->retornaMedida($dadosProdutos[$t]->medida_id)?></td>

Interestingly, I have no problems when I pass the outside variable as an argument to the anonymous function. I think this is what they mean with "capturing an out-of-scope variable" on C++'s lambdas.

felipsmartins
  • 13,269
  • 4
  • 48
  • 56
Ericson Willians
  • 7,606
  • 11
  • 63
  • 114
  • 3
    Tried looking at the [`use`](http://php.net/manual/en/functions.anonymous.php) keyword? – jardis Dec 24 '15 at 06:44
  • Passing as a parameter or making use of the `use` clause, this is how you can control the variables scope with PHP closures. That is just [standard PHP variable scope](http://php.net/manual/en/language.variables.scope.php). – hakre Dec 24 '15 at 09:48

1 Answers1

6

You can capture the variable you need with use.

$world = 'world';

$func = function() use ($world) {
    echo 'hello ' . $world;
};

$func();  
// hello world
danjam
  • 1,064
  • 9
  • 13