9
<?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

2
  • 2
    short answer: you don't. Commented Nov 9, 2009 at 4:43
  • The whole point of defining a variable within a particular scope is to limit access so that it's not accessible outside of that scope. So no, it's not possible. If you want to do this, then don't define it in local scope - use a class or global scope. Commented Nov 9, 2009 at 5:46

3 Answers 3

6

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;
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

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.
2

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?
  }
?>

3 Comments

The snag is that you have to define a global variable in global scope. So you cannot define it inside a function and then "export" it to global without having defined it in global before entering the function's scope. In your case that would be: <?php $g_two = null; function foo($one, $two){ global $g_two; ... ?>
This answer was like 12 years ago, so ...
So? 12 years are not a very long time and google hasn't forgotten it and I was just trying to help subsequent searchers, not criticising you.
0

I do use $global to access variables in my entire script.

Like this:

public function exist($id) {
    global $db;

    $query = "SELECT * FROM web_users_session where user_id='$id'";
    return $this->_check = $db->num_req($query);
}

1 Comment

Have you looked at another answers? You repeat them and also didn't use code for 2 functions

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.