title: PHP functions and variable scope in Smarty
body: <p>I'm working within <a href="http://www.smarty.net/docsv2/en/" rel="nofollow">Smarty 2.6.27</a>. There is something that prevents PHP functions from accessing global variables:</p>
  
  <pre><code>{php}
    $a = "should be global";
  
    function test(){
      global $a;
      echo $a;
    }
    test();
  {/php}
  </code></pre>
  
  <p>But the variable <code>$a</code> never makes it into the function. I've also done this:</p>
  
  <pre><code>{php}
    $a = "should be global";
  
    foreach ($GLOBALS as $key =&gt; $value) { 
       echo $key . "-" . $value;
    } 
  {/php}
  </code></pre>
  
  <p>But again, <code>$a</code> does not make it into the list of PHP globals. It seems that this is because Smarty runs PHP in some odd context--for example, <a href="http://www.smarty.net/docsv2/en/language.function.php.tpl" rel="nofollow">the documentation mentions</a> this:</p>
  
  <blockquote>
    <p>To access PHP variables in {php} blocks you will need to use the PHP
    global keyword.</p>
  </blockquote>
  
  <p>I don't really need to get access to other PHP globals, and I don't particularly want the scope of variables created here to go wider, I simply need to figure out how to use variables defined outside of the functions <em>in</em> the function. There will be a <em>lot</em> of these variables, so passing them as parameters is impractical.</p>