0

i have this class (simple one just for example):

<?
class Test {
  public function test1($a) {
    $gen = function() {
      $gen = function() {
        global $a; // no effect
        echo 'a='. $a; // how could i access $a from test1 parameter without passing?
      };
      $gen();
    };
    $gen();
  } 
};

$x = new Test();
$x->test1(123);

is there a way to access $a from test1 paramter inside last $gen function without passing it to the $gen() function?

5
  • I'm confused as to why you would want to access it without passing Commented Feb 5, 2013 at 4:09
  • just for syntaxtic sugar Commented Feb 5, 2013 at 4:10
  • @KiswonoPrayogo this code does not set value 123 to the function. See the example codepad.viper-7.com/8koTDz Commented Feb 5, 2013 at 4:11
  • yes, it is not.. the answer below is one i wanted :3 thanks anyway Commented Feb 5, 2013 at 4:19
  • if i pass the $a i would have to type it 4 times, using use keyword, i only need to write 2 times :3 this is one that i've been seeking Commented Feb 5, 2013 at 4:20

2 Answers 2

2

Anonymous functions in PHP don't have an implicit variable scope like JavaScript does, so you need to specify which variables from the parent scope are needed. You do this with the use syntax:

$var = 123;
$fn = function() use ($var) {
    // you can use $var here
}
$fn();

See also: Closures and scoping

Sign up to request clarification or add additional context in comments.

Comments

2

You are missing the use statement. Refere to the 3rd example on PHP's documentation on closures.

This will work:

<?php

class Test {
  public function test1($a) {
    $gen = function() use ($a) {
      $gen = function() use($a) {
        echo 'a='. $a; // how could i access $a from test1 parameter without passing?
      };
      $gen();
    };
    $gen();
  } 
};

$x = new Test();
$x->test1(123);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.