Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access variable from scope of another function?

Tags:

scope

php

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

like image 267
Mike Trpcic Avatar asked Nov 09 '09 04:11

Mike Trpcic


2 Answers

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;
  }
}
like image 62
Andrew Hare Avatar answered Oct 29 '22 05:10

Andrew Hare


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?
  }
?>
like image 32
Lukman Avatar answered Oct 29 '22 04:10

Lukman