Access variable from scope of another function?

2019-01-26 09:20发布

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

标签: php scope
3条回答
Deceive 欺骗
2楼-- · 2019-01-26 10:05

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;
  }
}
查看更多
聊天终结者
3楼-- · 2019-01-26 10:05

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);
}
查看更多
乱世女痞
4楼-- · 2019-01-26 10:11

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?
  }
?>
查看更多
登录 后发表回答