Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to access outer local variable in PHP?

Tags:

scope

php

Is it possible to access outer local varialbe in a PHP sub-function?

In below code, I want to access variable $l in inner function bar. Declaring $l as global $l in bar doesn't work.

function foo() {     $l = "xyz";      function bar()     {         echo $l;     }     bar(); } foo(); 
like image 597
Morgan Cheng Avatar asked Mar 09 '10 12:03

Morgan Cheng


1 Answers

You could probably use a Closure, to do just that...


Edit : took some time to remember the syntax, but here's what it would look like :

function foo() {     $l = "xyz";     $bar = function () use ($l)     {         var_dump($l);     };     $bar(); } foo(); 

And, running the script, you'd get :

$ php temp.php string(3) "xyz" 


A couple of note :

  • You must put a ; after the function's declaration !
  • You could use the variable by reference, with a & before it's name : use (& $l)

For more informations, as a reference, you can take a look at this page in the manual : Anonymous functions

like image 109
Pascal MARTIN Avatar answered Sep 19 '22 12:09

Pascal MARTIN