views:

128

answers:

2
<?php
  function foo($one, $two){
    bar($one);
  }

  function bar($one){
    echo $one;
    //How do I access $two from the parent function scope?
  }
?>

If I have the code above, how can I access the variable $two from within bar(), without passing it in as a variable (for reasons unknown).

Thanks,

Mike

+4  A: 

Make a class - you can declare $two as an instance field which will be accessible to all instance methods:

class Blah {
  private $two;
  public function foo($one, $two){
    this->$two = $two;
    bar($one);
  }

  public function bar($one){
    echo $one;
    // How do I access $two from the parent function scope?
    this->$two;
  }
}
Andrew Hare
While your answer didn't exactly answer the question (I'm still curious if it's possible outside of using a class), it DID remind me I was already inside a class, so I just made it a class member. Thanks a lot for the help.
Mike Trpcic
+1  A: 

A crude way is to export it into global scope, for example:

<?php
  function foo($one, $two){
    global $g_two;
    $g_two = $two;
    bar($one);
  }

  function bar($one){
    global $g_two;
    echo $g_two;
    echo $one;
    //How do I access $two from the parent function scope?
  }
?>
Lukman
I don't think this is a good advice, even tho it would work.
Carlos Lima